How to add new colum into Identity RoleClaims table (asp net core)

陌路散爱 提交于 2021-01-29 13:04:21

问题


I'm trying to add a column to the identity (asp net core) RoleClaims table but I find content just to extend the roles and users classes and not to RoleClaims. Could someone help with examples or point out content.


回答1:


You would need to create a new class to extend the RoleClaim. Here is an example of how to do it if your key type is string:

public class ApplicationRoleClaim : IdentityRoleClaim<string>
{
    public virtual ApplicationRole Role { get; set; }
}

You can add whatever new properties you want to this class then create a migration to add them as table columns.

You would also need to tell your IdentityDbContext to use this new class as well. Here is an example from the docs:

public class ApplicationDbContext
    : IdentityDbContext<
        ApplicationUser, ApplicationRole, string,
        ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin,
        ApplicationRoleClaim, ApplicationUserToken>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

EDIT:

With your custom ApplicationRoleClaim class, you could override OnModelCreating as well. This is an example from the docs:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ⋮
    modelBuilder.Entity<IdentityRoleClaim<string>>(b =>
    {
        b.ToTable("MyRoleClaims");
    });
    ⋮
}

Reference: Identity model customization in ASP.NET Core




回答2:


I made a demo with asp.net core 2.2 and it worked well ,try the following code , customize ApplicationRoleClaim to add other propertyies.

public class ApplicationRoleClaim: IdentityRoleClaim<string>
{
    public string Description { get; set; }
}

Then use DbSet<TEntity> class which represents a collection for a given entity within the model and is the gateway to database operations against an entity to add the new column to table

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {

    }

    public DbSet<ApplicationRoleClaim> ApplicationRoleClaim { get; set; }
}

Finally add-migration and update-database.



来源:https://stackoverflow.com/questions/57792378/how-to-add-new-colum-into-identity-roleclaims-table-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!