每次迁移的种子不同

时间:2014-12-22 12:02:10

标签: ef-migrations

是否可以为每次迁移提供不同的种子数据?

自第一次迁移以来,数据库数据可能已被更改。因此,不得在将来的迁移中使用它。但是在第一次迁移时我仍然想要它。

2 个答案:

答案 0 :(得分:0)

DbMigrationsConfiguration Seed方法将在应用每次迁移后运行,或者每次使用时都会运行,如果AutomaticMigrationsEnabled = true

答案 1 :(得分:0)

在程序包管理器控制台中使用以下命令添加新的空迁移:

Add-Migration DefaultAddressData

在此之后创建用于生成和恢复种子数据的up和down方法的sql脚本

namespace Northwind.CodeFirst.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class DefaultAddressData : DbMigration
    {
        public override void Up()
        {
            this.Sql(@"INSERT INTO dbo.Addresses(Name, AddressLine1, AddressLine2, City, State)
                       VALUES ('John', 'House address 1', 'street address 1', 'city 1', 'some state'),
                              ('Name 2', 'House address 2', 'street address 2', 'city 2', 'some state');
                      INSERT INTO dbo.Addresses(Name, AddressLine1, AddressLine2, City, State)
                       VALUES ('Name 3', 'House address 3', 'street address 1', 'city 2', 'some state');");

        }

        public override void Down()
        {
            this.Sql(@"DELETE FROM dbo.Addresses
                       WHERE NAME IN('John', 'Name 2', 'Name 3');");
        }
    }
}