存在种子代码时,无法回滚到以前的迁移

时间:2019-01-28 09:15:41

标签: entity-framework ef-code-first ef-migrations

我们使用Code First Migration有时回滚到以前的迁移很有用。

大多数情况下,像Update-Database -TargetMigration:name_of_migration这样的工作。

但是,如果某些迁移包含Seed代码,则无法正常工作。

错误:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.__HistorySeeds_dbo.__MigrationHistory_History_MigrationId_History_ContextKey". 

The conflict occurred in database "MYDB", table "dbo.__HistorySeeds". 
The statement has been terminated.

我的问题是在那种情况下该如何进行?

以下示例:

public partial class AddMyTable : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "MyTable",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Description = c.String(nullable: false, maxLength: 100),
                    CreatedById = c.String(maxLength: 100),
                    CreatedTime = c.DateTime(nullable: false)
                })
            .PrimaryKey(t => t.Id);

    }

    public override void Down()
    {
        DropTable("dbo.MyTable");
    }

    public void Seed(MyContext context)
    {
        context.MyTable.AddOrUpdate(x => x.Description, new MyTable { Description = "Aaaaa", CreatedById = "JOHN.DOE", CreatedTime = DateTime.Now });
        context.MyTable.AddOrUpdate(x => x.Description, new MyTable { Description = "Bbbbb", CreatedById = "JOHN.DOE", CreatedTime = DateTime.Now });
        context.MyTable.AddOrUpdate(x => x.Description, new MyTable { Description = "Ccccc", CreatedById = "JOHN.DOE", CreatedTime = DateTime.Now });

    }
  }
}

0 个答案:

没有答案