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

I’ve been upgrading our systems to use Entity Framework 4.1 code first.

I stumbled onto an issue where I had a table with multiple foreign keys pointing to the same table like so:

dbo.Companies can have Seller or Debtor as a CompanyType
dbo.SellerDebtors defines the relationship a Seller Company has with a Debtor Company.

If you have more than one navigation property of the same type, Entity Framework is not able to determine which navigation properties belong together.

You need to use the attribute InverseProperty to tell EF which navigation properties to use.

The model should be written like this:

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 virtual ICollection<SellerDebtorInfo> SellerDebtorInfos { get; set; }
    public virtual ICollection<SellerDebtorFile> SellerDebtorFiles { get; set; }    
}

public class Company
{
    public int CompanyId { get; set; }
    public string CompanyType { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<CompanyInfo> CompanyInfos { get; set; }
    public virtual ICollection<CompanyFile> CompanyFiles { get; set; }

    public virtual ICollection<SellerDebtor> SellerDebtorDebtorCompanies { get; set; }
    public virtual ICollection<SellerDebtor> SellerDebtorSellerCompanies { get; set; }
}
Advertisements

4 thoughts on “Multiple foreign keys pointing to same table in Entity Framework 4.1 code first

  1. I tried this example and still get the data created but objects are not error. I manually corrected the RI and the rest is working. Is there new EF download to fix this problem? I have 4.1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s