简体   繁体   English

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

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

I have the following classes, that already have their tables created and defined using EF migrations: 我有以下类,已经使用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; }
}

In the Request table, this properly created the FK FK_dbo.Request_dbo.Account_AccountID 在“ Request表中,此操作正确创建了FK FK_dbo.Request_dbo.Account_AccountID

Using SSMS, I can confirm the FK is setup properly. 使用SSMS,我可以确认FK已正确设置。

In order to be able to access the Request's one-to-many property from the Account entity, I added the following property to the AccountEntity class: 为了能够从Account实体访问Request's一对多属性,我向AccountEntity类添加了以下属性:

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

However, now EF suspects that I need to run migrations due to domain changes. 但是,现在EF怀疑由于域更改而需要运行迁移。

Here's the migration class that it creates, and wants to run: 这是它创建并想要运行的迁移类:

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

As you can see, EF seems to not recongize/respect that the FK relationshp has already been setup. 如您所见,EF似乎不承认/尊重FK关系已建立。

I don't suspect that any migrations need to be setup. 我不怀疑需要进行任何迁移。 The FK is already established, and I'm simply adding the collection "navigation" property. FK已经建立,我只是添加了集合“ navigation”属性。

Migrations need to be enabled for this project. 需要为此项目启用迁移。 EF version is 6, .NET 4.5. EF版本是6,.NET 4.5。

One possible way this can happen is if you have used fluent configuration like this: 发生这种情况的一种可能方法是,如果您使用过这样的流畅配置:

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

and forgot to update the .WithMany() to .WithMany(e => e.Requests) after introducing the collection navigation property, in which case EF considers two one-to-many relationships, hence adds a second FK column with default name. 并在引入集合导航属性后忘记将.WithMany()更新为.WithMany(e => e.Requests) ,在这种情况下,EF考虑了两个一对多的关系,因此添加了第二个FK列,其默认名称为。

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

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