【问题标题】:Add-Migration won't detect changes to foreign keyAdd-Migration 不会检测到外键的更改
【发布时间】:2014-10-08 13:45:36
【问题描述】:

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

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

迁移文件:

__migrationhistory 表:

之前

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);

【问题讨论】:

  • 我可以确认这个问题。重命名Using 属性是一个有效的“解决方案”。也许这是 EF 中的一个错误...

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


【解决方案1】:

正如我在评论中已经说过的,我可以重现这一点,但重命名 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 在重命名属性时创建的内容。

【讨论】:

  • 也许我们应该报告这个错误:)
  • 当我手动更改 Up() / Down() 方法时,发生了一些奇怪的事情。我收到以下错误:表 'mydb.dbo.people' 不存在。我检查了数据库,它就在那里。当我清空Up() / Down() 时,一切都恢复正常了......
  • 重命名属性会导致相同的“表 'mydb.dbo.people' 不存在。”错误:(
  • 这很奇怪。在我的测试项目中没有发生。尝试生成 SQL 脚本并通过 SSMS 手动执行?
  • 可能是因为我将表重命名为this.ToTable("...")。我将不得不在一个孤立的案例中进行测试。感谢您的帮助顺便说一句:)
猜你喜欢
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 2014-11-06
  • 1970-01-01
  • 2020-07-14
  • 2020-05-16
相关资源
最近更新 更多