Search code examples
c#asp.net-coreasp.net-core-identity

Customise Asp.Net Core ApiAuthorizationDbContext table names


I'm working with Asp.Net Core identity, and I want to change the tables names that are generated by the default ApiAuthorizationDbContext. For the sake of argument, let's say that I want to change AspNetRoleClaims to be MyRoleClaims.

My DbContext looks like this:

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

    }

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

I'm aware that if I inherit directly from IdentityDbContext then I can specify certain entities, but I can't see a way to do that using ApiAuthorizationDbContext. It appears that the only difference between the two are the following tables:

public DbSet<PersistedGrant> PersistedGrants { get; set; }
public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }

So, I suppose I could create my DbContext based on IdentityDbContext, and add these manually, but that feels like I'm re-inventing the wheel. Is there a way to specify these table names, or do I really need to build this manually from IdentityDbContext?


Solution

  • Override OnModelCreating in your ApiAuthorizationDbContext

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder); 
    
            modelBuilder.Entity<ApplicationUser>().ToTable("User");
            modelBuilder.Entity<IdentityRole>().ToTable("Role");
            modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
        }