Entity Framework 4.1 Code First中多个外键指向同一张表

17

我卡在了尝试编写Entity Framework 4.1的Code First模型上,涉及以下数据库关系。

以下是关系的可视化图形:enter image description here

dbo.[Companies]可以有卖方(Seller)或债务人(Debtor)作为公司类型。

dbo.[SellerDebtors]定义了卖方公司与债务人公司之间的连接。

我编写的代码基于原始的EF 4.0 POCO模型代码。这就是我想出的 - 这段代码无效。

public class SellerDebtor
{
    public int SellerDebtorId { get; set; }
    public int DebtorCompanyId { get; set; }
    public int SellerCompanyId { get; set; }

    public Company DebtorCompany { get; set; }
    public Company SellerCompany { get; set; }

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

}

目前,我遇到了以下错误:

System.Data.SqlClient.SqlException: Invalid column name 'DebtorCompany_CompanyId'.
Invalid column name 'SellerCompany_CompanyId'.
Invalid column name 'Company_CompanyId'.
Invalid column name 'Company_CompanyId1'.

理想情况下,我希望能够保持关系的命名。

我猜我需要设置一些属性,但我不确定该设置什么。


可能是Entity Framework Code First - two Foreign Keys from same table的重复问题。 - Michael Freidgeim
2个回答

20

EF无法按照约定确定你的两个类中的哪些导航属性是相互关联的,因此会创建4个关系(另一侧没有结束)而不是2个(两侧都有结果)。当你在同一个类中有多个相同类型的导航属性(在你的情况下是Company)时,就会出现这个问题。可以尝试以下方式来解决:

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(...)] 定义了关系的另一端导航属性,并显式地告诉 EF 哪些导航属性成对地属于一个关系。


3

非常高兴看到你发布了这个。我今天正需要这个流畅API的例子。 - Brandon
在我看来,这是最好的答案。流畅的API清晰明了,就像阳光明媚的一天。 - alex440

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接