1

How to change table names in ASP.net Identity 3.0?

I have searched but I didn't get any workable write up for Identity 3.0

and this How can I change the table names used by asp.net identity 3 (vnext)? is not working.

Community
  • 1
  • 1
Abubakar Ikram
  • 433
  • 9
  • 23

2 Answers2

4

You can do this easily by changing the entity mapping with extension method ToTable("TableName")on OnModelCreating of your DbContext:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<User>().ToTable("Users"); // Your custom IdentityUser class
    builder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
    builder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
    builder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
    builder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");
    builder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims");
    builder.Entity<IdentityRole>().ToTable("Roles");            
}

The only catch here is to remember to use the generics with the type of your identifier (string is default on AspNetCore.

Tanato
  • 895
  • 12
  • 23
-2

Just for documentation purpose, for the one who comes to this post on the years anyears on the future, (like me XD), The answer to the question:

How can I change default ASP.NET Identity table names in .NET CORE?

Can be solved as this

//Repeat with each table

   builder.Entity<ApplicationUser>(entity =>
   {
       entity.ToTable(name:"Users");
       entity.Property(e => e.Id).HasColumnName("UserId");

   });

Or can be solved like this

    modelBuilder.Entity<IdentityUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
    modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
    modelBuilder.Entity<IdentityUserRole>().ToTable("MyUserRoles");
    modelBuilder.Entity<IdentityUserLogin>().ToTable("MyUserLogins");
    modelBuilder.Entity<IdentityUserClaim>().ToTable("MyUserClaims");
    modelBuilder.Entity<IdentityRole>().ToTable("MyRoles");

But you can simplyfied with this method given by Alexandru Bucur on his blog and tested on netcore 2.2

     foreach (var entityType in modelBuilder.Model.GetEntityTypes())
     {
        var table = entityType.Relational().TableName;
         if (table.StartsWith("AspNet"))
         {
             entityType.Relational().TableName = table.Substring(6);
         }
     };

But this it's not longger support on netcore > 2.2, so, I need to fix it and this is the functional way on NetCore > 2.2

    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        var tableName = entityType.GetTableName();
        if (tableName.StartsWith("AspNet"))
        {
            entityType.SetTableName(tableName.Substring(6));
        }
    }

Choose what you prefeer and enjoy it, HappyCoding

sgrysoft
  • 588
  • 7
  • 14