entity framework自动迁移

第一步,建立测试项目,普通的WinForm类型,EntityMigration;

第二步,从NuGet为项目添加MySql.Data.Entity,由Oracle提供,我选择人气高的;

第三步,建立实体模型;

 1 using System.ComponentModel.DataAnnotations;
 2 
 3 namespace EntityMigration
 4 {
 5     public class Item
 6     {
 7         public long Id { get; set; }
 8 
 9         [MaxLength(30)]
10         public string Code { get; set; }
11 
12         [MaxLength(50)]
13         public string Label { get; set; }
14 
15     }
16 }

第四步,建立数据库上下文,注意添加数据库类型的注解;

 1 using System.Data.Entity;
 2 using MySql.Data.Entity;
 3 
 4 namespace EntityMigration
 5 {
 6     [DbConfigurationType(typeof(MySqlEFConfiguration))]
 7     class DatabaseContext:DbContext
 8     {
 9         public DatabaseContext():base("name=mysql")
10         {
11         }
12 
13         public DbSet<Item> Items { get; set; }
14 
15     }
16 }

第五步,建立自动迁移的配置;

 1 using System.Data.Entity.Migrations;
 2 
 3 namespace EntityMigration
 4 {
 5     class Configuration:DbMigrationsConfiguration<DatabaseContext>
 6     {
 7         public Configuration()
 8         {
 9             AutomaticMigrationsEnabled = true;
10             AutomaticMigrationDataLossAllowed = true;
11         }
12     }
13 }

第六步,在应用程序启动的地方添加迁移代码;

            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());

以上做完了,你会发现自动迁移并没有生效,因为你还差一步,就是访问一次数据库;

 1         static void Main()
 2         {
 3             Application.EnableVisualStyles();
 4             Application.SetCompatibleTextRenderingDefault(false);
 5 
 6             Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
 7 
 8             #region 让自动迁移生效的测试
 9 
10             using (var db = new DatabaseContext())
11             {
12                 var tem = db.Items.Where(x => x.Code == "1234");
13             }
14 
15             #endregion
16 
17             Application.Run(new Form1());
18         }
原文地址:https://www.cnblogs.com/jonney-wang/p/6219400.html