2011-06-17 81 views
1

在實體中使用代碼優先方法,是否可以建立綁定到單個外鍵的多個關係?實體框架4.1代碼優先 - 具有多重關係的外鍵?

例如,說我有以下類:

public class BuzzItem 
{ 
    public int  BuzzItemID  { get; set; } 
    public string Title   { get; set; } 
    public string Description  { get; set; } 

    // Collection of Comments posted about this BuzzItem (FOREIGN KEY) 
    public virtual ICollection<Comment> Comments { get; set; } 
} 

public class Merchant 
{ 
    public int  MerchantID  { get; set; } 
    public string Name   { get; set; } 

    // Collection of Comments posted about this Merchant (FOREIGN KEY) 
    public virtual ICollection<Comment> Comments { get; set; } 
} 

public class Comment 
{ 
    public int  CommentID  { get; set; } 
    public string Comment   { get; set; } 

    // These would both be a FOREIGN KEY to their respectivate tables 
    public virtual BuzzItem BuzzItemID { get; set; } 
    public virtual Merchant UserID { get; set; } 
} 

是否有可能取代單變量兩國外交關鍵變量,可以建立一個雙重關係,並接受一個BuzzItem或商人對象關係?

爲了簡潔起見,我從廢料中起草了這個例子,所以如果我在代碼中有任何拼寫錯誤,我很抱歉,但是我想要完成的總體想法很有希望。

回答

1

不,這是不可能的。 EF的行爲與數據庫完全相同 - FK與單個實體類型的單一關係緊密。順便說一句。導航屬性不是FK,FK隱藏在導航屬性的後面,但同樣如此 - 導航屬性不能在多個關係中共享。

+0

它是否可以嘗試類似於:'public virtual int SourceID {get;組; }'然後使用RTTI將它投射到BuzzItem或Merchant對象?如果是這樣,你有沒有關於如何實現它的提示? – 2011-06-17 05:33:01

1

使用this pattern,這可以通過使用table-per-type inheritance in EF來實現。

+0

+1,因爲這在技術上是我尋找的解決方案。但正如在你連接的另一個問題中一樣,一個實體超類除了擁有一個沒有公共屬性的EntityID變量以外沒有任何其他用途,正如他們指出的那樣,它不是一個好設計。但是,我並不是僅僅依靠嚴格的設計原則來阻止合法的解決方案,所以我可能會採用這種方式。儘管如此,仍然希望有一個更優雅的方法。 – 2011-06-17 12:49:43

相關問題