EF Code First Model字段改变数据库的字段也跟着自动改变 public class Context:DbContext { public Context():base("UserDB") { //自动创建表,如果Entity有改到就更新到表结构 Database.SetInitializer<Context>(new MigrateDatabaseToLatestVersion<Context, ReportingDbMigrationsConfiguration>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//这句是不要将EF生成的sql表名不要被复数 就是表名后面不要多加个S } internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<Context> { public ReportingDbMigrationsConfiguration() { AutomaticMigrationsEnabled = true;//任何Model Class的修改將会直接更新DB AutomaticMigrationDataLossAllowed = true; } } public DbSet<UserInfo> UserInfo { get; set; }
//数据库不存在时重新创建数据库 Database.SetInitializer(new CreateDatabaseIfNotExists<DbContext>()); //每次启动应用程序时创建数据库 Database.SetInitializer(new DropCreateDatabaseAlways<DbContext>()); //模型更改时重新创建数据库 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContext>()); //从不创建数据库 Database.SetInitializer<DbContext>(null);