http://www.entityframeworktutorial.net/code-first/code-based-migration-in-code-first.aspx = Code based Migration
http://www.entityframeworktutorial.net/code-first/automated-migration-in-code-first.aspx = Automated Migration
上边两篇文章分别介绍了DataMigration的两种方法。 下面简单总结一下步骤供自己使用。
VS Tools->package manager console
> enble-migration
执行上面步骤将在你的DBContext目录下生成一个Migrations/Configuration.cs文件。这个文件的。 Seed方法是当Migration完成以后执行的插入数据库的操作,可以放一些系统运行所需要的必须得数据
1 internal sealed class Configuration : DbMigrationsConfiguration2 { 3 public Configuration() 4 { 5 AutomaticMigrationsEnabled = true; 6 ContextKey = "Infrastructor.MainBoundedContext.UnitWorks.MainDBUnitWorkContext"; 7 } 8 9 protected override void Seed(Infrastructor.MainBoundedContext.UnitWorks.MainDBUnitWorkContext context)10 {11 // This method will be called after migrating to the latest version.12 13 // You can use the DbSet .AddOrUpdate() helper extension method 14 // to avoid creating duplicate seed data. E.g.15 //16 // context.People.AddOrUpdate(17 // p => p.FullName,18 // new Person { FullName = "Andrew Peters" },19 // new Person { FullName = "Brice Lambson" },20 // new Person { FullName = "Rowan Miller" }21 // );22 //23 context.Status.AddOrUpdate(p => p.Name,24 new Status { Name = "通过" },25 new Status { Name = "等待审批" }26 );27 }28 }
将以上构造函数Merge到自己的DBCOntext文件中
public MainDBUnitWorkContext(string connectionString): base(connectionString){//this.Configuration.ProxyCreationEnabled = false;this.Configuration.LazyLoadingEnabled = true;Database.SetInitializer(new MigrateDatabaseToLatestVersion("MyDBConnectionString"));}
> Add-Migration "MyTest"
添加新的migration,执行完成以后在migration目录下生成一个 20150101_Mytest.cs文件,其内部列举了这次DB Upgrade执行的升级和降级的操作
> Update-DataBase -script: 参数script 是执生成sql脚本,也可以不要这个参数,将直接更新数据库