[英]Entity Framework - Child with different parents
我正在使用EF 6,Code First。 我有一個“聯系”實體,一個“客戶”和一個“制造商”。 客戶和制造商都有聯系實體列表。 也許在開發過程中,可能會有更多具有聯系實體列表的實體。 我如何塑造聯系實體,以便沒有單獨的ID作為客戶和制造商的外鍵? 我想到的是這樣的:
public class Contact
{
[Key]
public int Id { get; set; }
...
public int ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Customer Customer { get; set; }
[ForeignKey("ParentId")]
public virtual Manufacturer Manufacturer { get; set; }
}
這可能嗎?
編輯:似乎並不是那么容易。 我所做的如下:
public class Customer
{
...
[InverseProperty("Customer")]
public virtual ICollection<Contact> Contacts { get; set; }
....
}
public class Manufacturer
{
...
[InverseProperty("Manufacturer")]
public virtual ICollection<Contact> Contacts { get; set; }
...
}
public class Contact
{
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Manufacturer Manufacturer { get; set; }
[ForeignKey("ParentId")]
public virtual Customer Customer { get; set; }
}
現在,我必須同時包括制造商和客戶,而不是制造商或客戶。 在ModelBuilder中放入“ ... HasOptional(...)”並不能解決問題。
????
您需要在客戶和制造商字段上使用InverseProperty屬性,例如
[InverseProperty("Id")]
[ForeignKey("ParentId")]
public virtual Customer Customer { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.