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

前端 未结 2 1213
花落未央
花落未央 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<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.

    0 讨论(0)
  • 2020-12-14 10:15

    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);
    
    0 讨论(0)
提交回复
热议问题