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.
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.
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);