Search code examples
authenticationentity-framework-coreblazor.net-8.0asp.net-core-identity

How can I change default AspNetUserLogins table to MyUserLogins table in Blazor web app on .NET 8, Login with individual account?


I created a Blazor web app with authentication type = Individual Account. It automatically maps to the default ASP.NET tables. Can I change the name of these tables to make it maps with my tables in database?

Blazor web app settings

ASP.NET default tables

I tried changing the ApplicationDbContext, but it does not work:

public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options)
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>().ToTable("MyUsers");
        modelBuilder.Entity<IdentityRole>().ToTable("MyRoles");
        modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("MyRoleClaims");
        modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("MyUserClaims");
        modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("MyUserLogins");
        modelBuilder.Entity<IdentityUserRole<string>>().ToTable("MyUserRoles");
        modelBuilder.Entity<IdentityUserToken<string>>().ToTable("MyUserTokens");
    }
}

Solution

  • [SOLVE]

    1. Update ApplicationDbContext.cs.

      public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
      {
       public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
       {
       }
      
       protected override void OnModelCreating(ModelBuilder modelBuilder)
       {
           base.OnModelCreating(modelBuilder);
      
           modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers");
      
           // Rename other Identity tables
           modelBuilder.Entity<IdentityRole>().ToTable("MyRoles");
           modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("MyRoleClaims");
           modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("MyUserClaims");
           modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("MyUserLogins");
           modelBuilder.Entity<IdentityUserRole<string>>().ToTable("MyUserRoles");
           modelBuilder.Entity<IdentityUserToken<string>>().ToTable("MyUserTokens");
      
           // If you want to rename columns, e.g., rename Id to UserId
           // modelBuilder.Entity<ApplicationUser>().Property(p => p.Id).HasColumnName("UserId");
       }
      }
      
    2. Open Package Manage Console and run these 2 command to Update tables in Database

       Add-Migration RenameIdentityTables
       Update-Database
      

    ***If you already have your table and don't want to update current table:

    1. Update ApplicationDbContext.cs as above
    2. Update table name in ApplicationDbContextModelSnapshot.cs