添加迁移无法检测到外键的更改

时间:2014-10-08 13:45:37

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

EF迁移似乎无法检测到我对模型所做的更改,因为它只会在运行Up() / Down()时生成空Add-Migration

数据库与我的迁移不同步。

迁移文件: Migration file

__ migrationhistory table: __migrationhistory table

之前

public class House {
    public virtual ICollection<Person> UsedBy { get; set; }
}

public class Car {
    // ...
}

public class Person {
    public int? UsingId { get; set; }
    public virtual House Using { get; set; }
}

映射

this.HasOptional(t => t.Using)
                .WithMany(t => t.UsedBy)
                .HasForeignKey(t => t.UsingId);

public class House {
    // removed
}

public class Car {
    // added
    public virtual ICollection<Person> UsedBy { get; set; }
}

public class Person {
    public int? UsingId { get; set; }
    // changed type
    public virtual Car Using { get; set; }
}

映射

this.HasOptional(t => t.Using)
                .WithMany(t => t.UsedBy)
                .HasForeignKey(t => t.UsingId);

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说,我可以重现这一点,但重命名Using属性也有帮助 如果这不是一个选项,您可以使用手动添加的以下代码进行迁移:

public override void Up()
{
    DropForeignKey("dbo.People", "UsingId", "dbo.Houses");
    AddForeignKey("dbo.People", "UsingId", "dbo.Cars", "Id");
}

public override void Down()
{
    DropForeignKey("dbo.People", "UsingId", "dbo.Cars");
    AddForeignKey("dbo.People", "UsingId", "dbo.Houses", "Id");
}

这是基于Add-Migration在重命名属性时创建的内容。