Warm tip: This article is reproduced from serverfault.com, please click

Custom Roles class for ApiAuthorizationDbContext

发布于 2020-11-29 21:19:58

For the past 2 days I have been trying to get ApiAuthorizationDbContext to set a custom IdentityRole. With IdentityDbContext this could be done as follows:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

In the blazor project template the declaration of the ApplicationDbContext is the following:

public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
    public ApplicationDbContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
    {
    }
}

How can I do something similar with the ApiAuthorizationDbContext. I can not find this kind of support from the ApiAuthorizationDbContext class.

Thanks.

Questioner
pitaridis
Viewed
0
pitaridis 2020-12-02 07:39:24

I did not find a way to have my custom role class but I found a way to solve my problem and add properties to the existing IdentityRole class and will answer my question just in case someone else needs to do something similar. The solution to this problem is the Shadow properties.

For example if I want to create a DateTime property to the IdentityRole class we can use the following code in our DBContext class.

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<IdentityRole>().Property<DateTime>("LastUpdated");
    base.OnModelCreating(builder);
}

Now we can access the property like this:

context.Entry(myRole).Property("LastUpdated").CurrentValue = DateTime.Now;

It is not as easy as having a custom class but at least it gives me the opportunity to have custom properties for the IdentityRole class.