Search code examples
asp.net-coreidentityrolesclaims

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


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.


Solution

  • 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