C# 如何使用数据库优先实体框架更改表名

C# 如何使用数据库优先实体框架更改表名,c#,asp.net,.net,entity-framework,asp.net-identity,C#,Asp.net,.net,Entity Framework,Asp.net Identity,这与此问题类似,但使用数据库优先实体框架而不是代码优先: 在“代码优先”方法中,您可以覆盖OnModelCreating并执行类似操作,以便将用户信息保存在MyUsers表中,而不是保存在默认的AspNetUsers表中: modelBuilder.Entity<IdentityUser>().ToTable("MyUsers") modelBuilder.Entity().ToTable(“MyUsers”) 在database first方法中,我手动创建了MyUsers表

这与此问题类似,但使用数据库优先实体框架而不是代码优先:

在“代码优先”方法中,您可以覆盖OnModelCreating并执行类似操作,以便将用户信息保存在MyUsers表中,而不是保存在默认的AspNetUsers表中:

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

在database first方法中,我手动创建了MyUsers表,但由于未调用OnModelCreating,我不知道如何配置要保存到新表中的数据?

在重写OnModelCreating时,您可以遵循代码优先的方法添加行:

System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);
System.Data.Entity.Database.SetInitializer(null);
上面的行将AspNetIdentity实体链接到您的表,而无需重新创建表

代码示例:

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);
}
protectedoverride void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
基于模型创建(modelBuilder);
modelBuilder.Entity().ToTable(“用户角色”);
modelBuilder.Entity().ToTable(“用户登录”);
modelBuilder.Entity().ToTable(“用户声明”);
modelBuilder.Entity().ToTable(“角色”);
System.Data.Entity.Database.SetInitializer(null);
}

Hi Freerider。未调用OnModelCreating方法?我想这是因为我使用的是数据库优先的方法,这是我的要求。这是从IdentityDbContext继承的数据库上下文(在我的示例中是ApplicationDbContext)?实际上不是,我是从DbContext继承的。我需要从IdentityDbContext继承吗?我现在确实继承了它,而OnModelCreating仍然没有被调用。我认为,如果我将连接字符串更改为代码优先字符串,它将被调用,但我需要以数据库优先的方式执行此操作。还有建议或链接到一个有用的例子?@Bob你有没有找到一种方法让它使用DatabaseFirst方法?你在什么地方找到这个答案了吗?