【问题标题】:EF re-adding FK columns after adding ICollection navigation property添加 ICollection 导航属性后 EF 重新添加 FK 列
【发布时间】:2017-12-21 19:07:39
【问题描述】:

我有以下类,它们已经使用 EF 迁移创建和定义了它们的表:

[Table("Account")]
public class AccountEntity
{
    [Key]
    public virtual int Id { get; set; }
}

[Table("Request")]
public class RequestEntity
{
    [Key]
    public virtual int Id { get; set; }

    public int? AccountID { get; set; }

    [ForeignKey("AccountID")]
    public virtual AccountEntity Account { get; set; }
}

Request 表中,这正确地创建了 FK FK_dbo.Request_dbo.Account_AccountID

使用 SSMS,我可以确认 FK 设置正确。

为了能够从Account 实体访问Request's 一对多属性,我在AccountEntity 类中添加了以下属性:

public virtual ICollection<RequestEntity> Requests { get; set; }

但是,现在 EF 怀疑由于域更改我需要运行迁移。

这是它创建并希望运行的迁移类:

public partial class RequestUpdate : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.Request", "AccountEntity_Id", c => c.Int());
        CreateIndex("dbo.Request", "AccountEntity_Id");
        AddForeignKey("dbo.Request", "AccountEntity_Id", "dbo.Account", "Id");
    }

    public override void Down()
    {
        DropForeignKey("dbo.Request", "AccountEntity_Id", "dbo.RealtorAccount");
        DropIndex("dbo.Request", new[] { "AccountEntity_Id" });
        DropColumn("dbo.Request", "AccountEntity_Id");
    }
}

如您所见,EF 似乎不承认/尊重 FK 关系已经设置。

我不怀疑需要设置任何迁移。 FK 已经建立,我只是添加集合“导航”属性。

需要为此项目启用迁移。 EF 版本为 6,.NET 4.5。

【问题讨论】:

  • 有没有相关的 Fluent API 配置未在帖子中展示?

标签: c# .net entity-framework entity-framework-6


【解决方案1】:

发生这种情况的一种可能方式是,如果您使用了这样的流畅配置:

modelBuilder.Entity<RequestEntity>()
    .HasOptional(e => e.Account)
    .WithMany();

在引入集合导航属性后忘记将.WithMany() 更新为.WithMany(e =&gt; e.Requests),在这种情况下,EF 考虑 两个 一对多关系,因此添加了第二个 FK 列默认名字。

【讨论】:

    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多