2014-09-01 60 views
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(...)」並不能解決問題。

?????

回答

1

您需要在客戶和製造商字段上使用InverseProperty屬性,例如,

[InverseProperty("Id")] 
[ForeignKey("ParentId")] 
public virtual Customer Customer { get; set; } 

Read about it here.

+0

錯過了 「InverseProperty」 屬性,現在它正在工作。謝謝! – okieh 2014-09-01 11:33:02