Multiple foreign keys pointing to same table in Entity Framework 4.1 code first

走远了吗. 提交于 2019-11-28 20:33:47

EF is not able to determine by convention which navigation properties on your 2 classes belong together and creates 4 relationships (without an end on the other side) instead of 2 (with ends on both sides). This problem occurs always when you have more than one navigation property of the same type (Company in your case) in the same class. You could try to fix this the following way:

public class SellerDebtor
{
    public int SellerDebtorId { get; set; }
    [ForeignKey("DebtorCompany")]
    public int DebtorCompanyId { get; set; }
    [ForeignKey("SellerCompany")]
    public int SellerCompanyId { get; set; }

    [InverseProperty("SellerDebtorDebtorCompanies")]
    public Company DebtorCompany { get; set; }
    [InverseProperty("SellerDebtorSellerCompanies")]
    public Company SellerCompany { get; set; }

    public ICollection<SellerDebtorInfo> SellerDebtorInfos { get; set; }
    public ICollection<SellerDebtorFile> SellerDebtorFiles { get; set; }    
}

[InverseProperty(...)] defines the navigation property on the other end of the relationship and it tells EF explicitely which pairs of navigation properties belong together in a relationship.

Desmond

This blog has the example using Fluent API configurations.

Multiple foreign keys within same table using CodeFirst Entity Framework and Fluent API

modelBuilder.Entity<Branch>().HasOptional(b => b.PrimaryContact)         
            .WithMany(a => a.PrimaryContactFor).HasForeignKey(b=>b.PrimaryContactID);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!