实体框架迁移检测不存在的内容

时间:2016-09-06 08:01:26

标签: c# asp.net-mvc entity-framework ef-migrations

我正在使用Entity Framework和代码优先方法。

我创建了一个我映射为表的类:

modelBuilder.Entity<CdrFile>()
    .ToTable("cdrFile", schemaName)
    .HasKey(f => new { f.Id });

我创建了迁移CdrFileMigration。这是最后迁移。

public override void Up()
{
    CreateTable(
        "administration.cdrFiles",
        c => new
            {
                id = c.Int(nullable: false, identity: true),
                name = c.String(),
                fileNameWithExtension = c.String(), // <-- See this line
                url = c.String(),
                serviceType = c.String(),
                date = c.DateTime(nullable: false),
                state = c.Int(nullable: false),
                operatorName = c.String(),
                acquisitionDate = c.DateTime(nullable: false),
            })
        .PrimaryKey(t => t.id);
}

然后我更新了db。 一段时间过去了,我更改了实体CdrFile删除列。 同时没有创建迁移。所以我将数据库更新为之前的版本。我修改了CdrFileMigration删除列:

public override void Up()
{
    CreateTable(
        "administration.cdrFiles",
        c => new
            {
                id = c.Int(nullable: false, identity: true),
                name = c.String(),
                //fileNameWithExtension = c.String(), // <-- I removed this line
                url = c.String(),
                serviceType = c.String(),
                date = c.DateTime(nullable: false),
                state = c.Int(nullable: false),
                operatorName = c.String(),
                acquisitionDate = c.DateTime(nullable: false),
            })
        .PrimaryKey(t => t.id);
}

我再次将数据库更新到上次迁移。 数据库已正确创建,但如果我再次运行Add-Migration命令,则会生成此文件

public partial class aa : DbMigration
{
    public override void Up()
    {
        DropColumn("administration.cdrFiles", "fileNameWithExtension");
    }

    public override void Down()
    {
        AddColumn("administration.cdrFiles", "fileNameWithExtension", c => c.String());
    }
}

为什么呢?我预计会有空迁移。事实如果我运行此迁移,我得到一个错误:&#34;没有找到要删除的fileNameWithExtension列&#34; ... 有人可以帮帮我吗?

谢谢

1 个答案:

答案 0 :(得分:2)

问题是,在将数据库更新到最后一个版本之后,您没有再次运行Add-Migration

EF在数据库中保留模型的快照。运行Add-Migration时会更新此快照。仅返回旧版本并仅编辑旧的迁移文件是不够的。

要解决您的问题,请使用Add-Migration创建一个空迁移。这将更新数据库中的快照。例如,您只需删除已创建的迁移中的DropColumn语句,然后Update-Database即可。如果您再次运行Add-Migration,则不再生成DropColumn语句。

总结一下,编辑现有迁移的正确方法是:

  1. Update-Database -TargetMigration {Name of migration before migration to be edited}
  2. 删除要修改的迁移文件(将UpDown的内容复制到剪贴簿)
  3. 使用Add-Migration再次生成迁移。根据需要进行修改。
  4. Update-Database申请迁移