Mvc5 EF6 CodeFirst Mysql (二) 修改数据模型

1.开发环境中修改模型,在DbContext中加入静态构造函数,并设置初始化模式:

static DemoDbContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DemoDbContext>());
        }
View Code

  如果是Mysql,需要在DbContext加上 [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 属性,否则操作数据库时会报错,更改结束后,注释掉就可以了

  新增类时需要在DbContext添加该类的引用属性,如:新增Department类:

public DbSet<Department> Departments { get; set; }
View Code

2.生成环境中数据迁移

  2.1 首先安装 Enitity Framework:Install-Package EntityFramework

  2.2 修改DbContext静态构造函数:

 static DemoDbContext()
        {
            Database.SetInitializer<DemoDbContext>(null);
        }
View Code

  2.3 在程序包管理器控制台,执行语句:

PM> Enable-Migrations -EnableAutomaticMigrations

  这时会在工程下建立文件夹:Migrations 和 Configuration.cs 文件

  internal sealed class Configuration : DbMigrationsConfiguration<MvcDemo.DAL.DemoDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(MvcDemo.DAL.DemoDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.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类:

   using System;
    using System.Data.Entity.Migrations;
    
    public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            DropColumn("dbo.Student", "Email");
            DropColumn("dbo.Student", "Score");
        }
        
        public override void Down()
        {
            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 class City
    {
        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. 参考资料

  EF Code First Migrations数据库迁移

  Code First Migrations

  4.源码

  MvcDemo.rar

  

posted on 2016-04-12 13:25  DeepSpace  阅读(325)  评论(0编辑  收藏  举报