zoukankan      html  css  js  c++  java
  • 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         }
  • 相关阅读:
    各种颜色的英文代码
    颜色代码简集
    [转]怎么成为优秀的软件模型设计者
    控件禁用
    jQuery图片播放插件ColorBox使用方法
    5个好玩的在线HTML5游戏【部分附源码下载】
    各大网站架构总结笔记(续)
    Web开发基础务实之《ASP.NET战役完胜表彰晚会(一)》
    iview Form自动跳转到校验不通过的地方
    C++与Java比较
  • 原文地址:https://www.cnblogs.com/jonney-wang/p/6219400.html
Copyright © 2011-2022 走看看