1
我使用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」 屬性,現在它正在工作。謝謝! – okieh 2014-09-01 11:33:02