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

前端 未结 2 1215
花落未央
花落未央 2020-12-14 09:42

I\'m stuck at trying to write the Entity Framework 4.1 code first model for the following DB relationship.

Here is a visual of the relationship.

2条回答
  •  感情败类
    2020-12-14 10:04

    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 SellerDebtorInfos { get; set; }
        public ICollection 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.

提交回复
热议问题