简体   繁体   中英

How to change table name using database first Entity Framework

This is similar to this question but with using database first entity framework instead of code first: How can I change the table names when using Visual Studio 2013 ASP.NET Identity?

In the code first approach you can override OnModelCreating and do something like this so that the user info is saved in MyUsers table instead of the default AspNetUsers:

modelBuilder.Entity<IdentityUser>().ToTable("MyUsers")

In the database first approach I have manually created the MyUsers table but because OnModelCreating does not get called I don't know how to configure the data to be saved into my new table?

You can follow the Code First approach an when overriding the OnModelCreating add the line:

System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);

The line above will link the AspNetIdentity entities to your tables without re-creating the tables.

Code Example:

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

    modelBuilder.Entity<ApplicationUserRole>().ToTable("UserRoles");
    modelBuilder.Entity<ApplicationUserLogin>().ToTable("UserLogins");
    modelBuilder.Entity<ApplicationUserClaim>().ToTable("UserClaims");
    modelBuilder.Entity<ApplicationRole>().ToTable("Roles");

    System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM