42

I've started with .NET Core, in MVC 5 I changed default table names for example: AspNETUsers to Users in this way and it worked perfectly: In IdentityModels Class I dded:

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>().ToTable("Users").Property(p => p.Id).HasColumnName("UserId");
        modelBuilder.Entity<ApplicationUser>().ToTable("Users").Property(p => p.Id).HasColumnName("UserId");
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
    }

But it does not work in ASP.NET CORE (MVC 6). Can Anyone help me? Thanks a lot.

Archil Labadze
  • 4,049
  • 4
  • 25
  • 42
  • 2
    Please don't use :NET Core as synonym for ASP.NET Core! .NET Core is a runtime, like .NET 4.x runtime. ASP.NET Core on the other side is an framework/webstack and runs on **BOTH**, .NET Core and .NET >=4.5.1 – Tseng Jan 03 '17 at 18:06
  • @Tseng , I'm learning Core, sure where is lot of differences between ASP.NET and Core. – Archil Labadze Jan 03 '17 at 19:35

11 Answers11

32

-To change the names of those tables ( IdentityUserRole<Tkey>, IdentityUserToken<Tkey>, IdentityRoleClaim<Tkey>, IdentityUserClaim<Tkey>, IdentityUserLogin<Tkey>) you have to specify the type of TKey(The type used for the primary key ) which is string(GUID) by default even if you didn't change it.

-If you want to change the primary key from GUID to int https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>(entity =>
        {
            entity.ToTable(name: "User");         
        });

        builder.Entity<IdentityRole>(entity =>
        {
            entity.ToTable(name: "Role");
        });
        builder.Entity<IdentityUserRole<string>>(entity =>
        {
            entity.ToTable("UserRoles");
          //in case you chagned the TKey type
          //  entity.HasKey(key => new { key.UserId, key.RoleId });
        });

        builder.Entity<IdentityUserClaim<string>>(entity =>
        {
            entity.ToTable("UserClaims");
        });

        builder.Entity<IdentityUserLogin<string>>(entity =>
        {
            entity.ToTable("UserLogins");
             //in case you chagned the TKey type
          //  entity.HasKey(key => new { key.ProviderKey, key.LoginProvider });       
 });

        builder.Entity<IdentityRoleClaim<string>>(entity =>
        {
            entity.ToTable("RoleClaims");

        });

        builder.Entity<IdentityUserToken<string>>(entity =>
        {
            entity.ToTable("UserTokens");
            //in case you chagned the TKey type
           // entity.HasKey(key => new { key.UserId, key.LoginProvider, key.Name });

        });
    }
Ahmed Al Jabry
  • 1,367
  • 13
  • 9
  • Code-only answers are discouraged on SO. Can you use a few words and explain in how far this solves the issue?! – ImportanceOfBeingErnest May 24 '17 at 11:38
  • I added the above code to my asp.net core 2.0 mvc app. Cleaned and rebuilt the project and deleted the Migrations folder, then ran update-database in the nuget console and it still created the identity tables using the original AspNet* names. – alexb Sep 14 '17 at 15:05
  • Hi Alexb, I created new .NET Core 2.0 and I used the same code to change default ASP.NET identity tables names and it's working fine with me. Did you check ApplicationDbContextModelSnapshot to see if your migration succeed with the new tables names or not ? – Ahmed Al Jabry Oct 31 '17 at 07:41
  • Didn't work for me either. ApplicationDbContextModelSnapshot shows the original names, such as "AspNetUsers" – Christopher Nov 30 '17 at 06:30
  • 2
    Ah, my mistake was not calling base.OnModelCreating() before these statements. I used this format though: https://stackoverflow.com/a/41634288/13700 – Christopher Nov 30 '17 at 06:40
  • 1
    been struggling with this, made the same mistake and called `base.OnModelCreating()` after the configrations. this solved my problem. – Niklas Mar 08 '18 at 19:38
  • What about calling `!await _context.Users.AnyAsync()` of `Microsoft.AspNetCore.Identity.EntityFrameworkCore` Then it fails because it will be looking for Users instead of the name you've changed it in.. any suggestions? – Rafael Dec 28 '18 at 16:20
27

Try to change binding to

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

       });
Set
  • 47,577
  • 22
  • 132
  • 150
  • 6
    I'm 4 years late to the party, but nobody has referenced the official Microsoft docs for doing this, so here: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0#customize-the-model – JED Aug 01 '21 at 20:08
14

A complete list for ASP.Net Core 2/2.1, based on @ahmed-al-jabry 's answer.

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

    // Override default AspNet Identity table names
    modelBuilder.Entity<User>(entity => { entity.ToTable(name: "Users"); });
    modelBuilder.Entity<IdentityRole>(entity => { entity.ToTable(name: "Roles"); });
    modelBuilder.Entity<IdentityUserRole<string>>(entity => { entity.ToTable("UserRoles"); });
    modelBuilder.Entity<IdentityUserClaim<string>>(entity => { entity.ToTable("UserClaims"); });
    modelBuilder.Entity<IdentityUserLogin<string>>(entity => { entity.ToTable("UserLogins"); });
    modelBuilder.Entity<IdentityUserToken<string>>(entity => { entity.ToTable("UserTokens"); });
    modelBuilder.Entity<IdentityRoleClaim<string>>(entity => { entity.ToTable("RoleClaims"); });
}
mark.monteiro
  • 2,609
  • 2
  • 33
  • 38
Andriod
  • 1,239
  • 12
  • 18
  • Do you have for Asp.Core 2.1? – Bruno Henri Aug 06 '18 at 17:16
  • works with 2.2. had interesting issue recently. generated two roles tables. one: `aspnet_roles` and `Role`. the problem was that I used: `builder.Entity>(entity => { entity.ToTable("Role"); });` instead of generic `builder.Entity(entity => { entity.ToTable("Role"); });`. hope that helps anyone – Andrey Borisko Dec 19 '18 at 15:56
  • Works well with core 3.1 too. – DavidC Jul 14 '20 at 23:49
6

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
5
 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<IdentityUser>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityUserRole<string>>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityRole<string>>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityUserClaim<string>>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityUserLogin<string>>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityUserToken<string>>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityRole>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityRoleClaim<string>>(b =>
            {
                b.ToTable("ANYName");
            });
            modelBuilder.Entity<IdentityUserRole<string>>(b =>
            {
                b.ToTable("ANYName");
            });
        }

Add this method in ApplicationDbContext and add-migration to create changes and then update database to save changes.

Ishan
  • 285
  • 2
  • 8
2

I am adding a second answer, because many people will hit this when trying to change table names in .NET core 1, 2, 3 and .NET 5

The process is pretty straightforward and well explained in the docs.

For those needing quick fix:

  1. Inherit all your models which you want to change( default Microsoft authorization comes with 7 models ). For example changing AspNetUsers to User and AspNetRoles to Role you can do the following in your existing models:

     public partial class User : IdentityUser<int>
     {
         // code
     }
    
     public partial class Role : IdentityRole<int>
     {
         // code
     }
    

In this example I am changing the primary key type also because the default is nvarchar.

  1. In your context inherit from IdentityDbContext and use the same type as argument:

     public class AppDbContext : IdentityDbContext<User, Role, int>
     {
         // code
     }
    
  2. Next we have to update ConfigureServices in StartUp to use the new User class:

      services.AddDefaultIdentity<User, Role>()
      .AddEntityFrameworkStores<AppDbContext>();
    

Then if want need you migrate to update/create database. Depends if this is a new or old project.

Note: If you are currently using authentication in your project like UserManager or SignInManager you have to change their generic arguments to the new ones like so:

SignInManager<User>
UserManager<User>

Hope that helps :)

Ivaylo
  • 467
  • 6
  • 19
2

There are further 2 steps required to apply changes:

  • Apply Add-Migration
  • Update-database
Yawar Ali
  • 239
  • 3
  • 4
1

To update default table names IdentityModels Class MVC

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>().ToTable("Users").HasKey(x => x.Id);
        modelBuilder.Entity<ApplicationUser>().ToTable("Users").HasKey(x => x.Id);
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles").HasKey(x => x.RoleId);;
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins").HasKey(x => x.UserID);;
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims").HasKey(x => x.Id);;
        modelBuilder.Entity<IdentityRole>().ToTable("Roles").HasKey(x => x.Id);;
    }
Kishore Kumar
  • 21,449
  • 13
  • 81
  • 113
Bharat Kumar
  • 97
  • 1
  • 2
0

For MVC5 IdentityModels

protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);

            builder.Entity<IdentityUser>().Table("Users").Key(x => x.Id);
            builder.Entity<ApplicationUser>().Table("Users").Key(x => x.Id);
            builder.Entity<IdentityUserRole>().Table("UserRoles").Key(x => x.RoleId); ;
            builder.Entity<IdentityUserLogin>().Table("UserLogins").Key(x => x.UserId); ;
            builder.Entity<IdentityUserClaim>().Table("UserClaims").Key(x => x.Id); ;
            builder.Entity<IdentityRole>().Table("Roles").Key(x => x.Id); ;

        }
Bharat Kumar
  • 97
  • 1
  • 2
0

There is one extra note : I customized all of my identity tables name but it didn't apply. base on Microsoft reference you have to use base.OnModelCreating(builder); before your customization

To change the names of tables and columns, call base.OnModelCreating. Then, add configuration to override any of the defaults. For example, to change the name of all the Identity tables:

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

    modelBuilder.Entity<IdentityUser>(b =>
    {
       b.ToTable("MyUsers");
    });

    modelBuilder.Entity<IdentityUserClaim<string>>(b =>
    {
        b.ToTable("MyUserClaims");
    });

    modelBuilder.Entity<IdentityUserLogin<string>>(b =>
    {
        b.ToTable("MyUserLogins");
    });

    modelBuilder.Entity<IdentityUserToken<string>>(b =>
    {
        b.ToTable("MyUserTokens");
    });

    modelBuilder.Entity<IdentityRole>(b =>
    {
        b.ToTable("MyRoles");
    });

    modelBuilder.Entity<IdentityRoleClaim<string>>(b =>
    {
        b.ToTable("MyRoleClaims");
    });

    modelBuilder.Entity<IdentityUserRole<string>>(b =>
    {
        b.ToTable("MyUserRoles");
    });
}
Amirhossein Yari
  • 2,054
  • 3
  • 26
  • 38
0

In Entity Framework Core Version 6 this works fine:

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

    foreach (var entity in builder.Model.GetEntityTypes())
    {
        // Replace table names
        entity.SetTableName(entity.GetTableName().ToSnakeCase());
    }
}