繁体   English   中英

添加ICollection导航属性后,EF重新添加FK列

[英]EF re-adding FK columns after adding ICollection navigation property

我有以下类,已经使用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已经建立,我只是添加了集合“ navigation”属性。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM