1.开发环境中修改模型,在DbContext中加入静态构造函数,并设置初始化模式:
staticDemoDbContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
}
View Code
如果是Mysql,需要在DbContext加上 [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 属性,否则操作数据库时会报错,更改结束后,注释掉就可以了
新增类时需要在DbContext添加该类的引用属性,如:新增Department类:
public DbSet Departments { get; set; }
View Code
2.生成环境中数据迁移
2.1 首先安装 Enitity Framework:Install-Package EntityFramework
2.2 修改DbContext静态构造函数:
staticDemoDbContext()
{
Database.SetInitializer(null);
}
View Code
2.3 在程序包管理器控制台,执行语句:
PM> Enable-Migrations -EnableAutomaticMigrations
这时会在工程下建立文件夹:Migrations 和 Configuration.cs 文件
internal sealed class Configuration : DbMigrationsConfiguration{publicConfiguration()
{
AutomaticMigrationsEnabled= true;
}protected override voidSeed(MvcDemo.DAL.DemoDbContext context)
{//This method will be called after migrating to the latest version.//You can use the DbSet.AddOrUpdate() helper extension method//to avoid creating duplicate seed data. E.g.//
//context.People.AddOrUpdate(//p => p.FullName,//new Person { FullName = "Andrew Peters" },//new Person { FullName = "Brice Lambson" },//new Person { FullName = "Rowan Miller" }//);//}
}
View Code
2.4 执行语句:(为测试效果,删除了Student类中的Email和Score属性)
PM> Add-Migration InitialCreate
此时会自动生成InitialCreate类:
usingSystem;usingSystem.Data.Entity.Migrations;public partial classInitialCreate : DbMigration
{public override voidUp()
{
DropColumn("dbo.Student", "Email");
DropColumn("dbo.Student", "Score");
}public override voidDown()
{
AddColumn("dbo.Student", "Score", c => c.Double(nullable: false));
AddColumn("dbo.Student", "Email", c => c.String(unicode: false));
}
}
View Code
2.5 执行语句:Update-Database -Verbose 更改即应用到数据库中
2.6 新增类(表)
2.6.1 新增类 City,并在DbContext类中引用实例
public classCity
{public string ID { get; set; }public string Name { get; set; }
}
View Code
2.6.2 执行语句
PM> Add-Migration AddCity
2.6.3 执行语句
PM> Update-Database -Verbose
查看数据,City表已经添加
3. 参考资料
4.源码