EF Code First 数据迁移配置

这里我想讲清楚code first 数据迁移的两种模式,还有开发环境和生产环境数据迁移的最佳实践。

1.1 数据迁移综述

EF Code first 虽然已经有了几种不同的数据库初始化策略,但是大部分策略都会造成现有的数据丢失,所以如果我们想更新实体的结构,但是保留数据的话,EF提供了一个数据迁移的工具,它使用了新的数据库初始化策略叫做 MigrateDatabaseToLatestVersion,启用数据迁移之后,需要把数据库初始化策略修改为此策略。

一共有两种迁移模式:

  • Automated Migration
  • Code-based Migration

2.1 Automated Migration 自动化迁移

自动化迁移的配置比较简单,主要分为两个内容:

  1. 开启自动迁移
  2. 修改数据库初始化策略

开启自动迁移可以执行命令

enable-migrations –EnableAutomaticMigration:$true

可以在Configuration.class中手动配置,具体代码可以参考下面的代码

修改数据库自动迁移即下:

  public SchoolDBContext(): base("SchoolDB") 
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext, EF6Console.Migrations.Configuration>());
    }

2.2 Code-based Migration

主要分为以下几个内容:

  1. 启用迁移 :Enable-Migrations
  2. 添加迁移 :Add-Migration
  3. 执行迁移 : Update-Database
  4. 回滚 : update-database -TargetMigration:

Enable-Migrations

启用迁移之后,会在项目中新建 Migrations文件夹,下面有Configuration.class

    internal sealed class Configuration : DbMigrationsConfiguration<EFCodeFirst详细问题.DataBaseEntities>
    {
        public Configuration()
        {
         AutomaticMigrationsEnabled = true;
         AutomaticMigrationDataLossAllowed = true;
         ContextKey = "EFCodeFirst详细问题.DataBaseEntities";
        }

        protected override void Seed(EFCodeFirst详细问题.DataBaseEntities 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.
        }
    }

可以在构造函数中配置自动迁移,允许数据丢失等内容,重写的Seed方法看注释是在迁移到最后版本之后的执行函数,可以进行初始化数据等操作。

Add-Migration

添加迁移后,在configuration.class同级目录会生成一个升级脚本的C#的表达,其中用两个函数up和down,up是升级操作,down是回滚操作,我们也可以在其中编辑自己的代码,这也是迁移中比较灵活的地方。

  public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Schools",
                c => new
                    {
                        SchoolID = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t => t.SchoolID);
            
            CreateTable(
                "dbo.Students",
                c => new
                    {
                        StudentID = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        Age = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.StudentID);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.Students");
            DropTable("dbo.Schools");
        }
    }

Update-Database

这个没什么好说的,就是执行数据迁移--updateToLastVersion,有一个点就是在命令后面加上–verbose,可以看见执行的具体的sql脚本,对于定位错误还是很有用的

update-database -TargetMigration: 就是回滚到指定版本,这个还没玩过。

原文地址:https://www.cnblogs.com/codersun/p/8624977.html