2013-05-18 163 views
1

首先,我想說明我確實看到這個問題A LOT。我瞭解可能存在重複,但我已搜索和搜索,但我沒有找到正確的解決方案。實體框架ForeignKey問題

public class Members 
{ 
    public enum Statuses 
    { 
     APPLIED, 
     ACTIVE, 
     SUSPENDED, 
     DELETED 
    } 

    [Key] 
    public int ID { get; set; } 
    [Required] 
    public string UName { get; set; } 
    public int RecruiterID { get; set; } 
    public int AuditorID { get; set; } 
    public virtual ICollection<AuditorComments> AuditorComments { get; set; } 
    [Required] 
    public Statuses Status { get; set; } 
    [Timestamp] 
    public Byte[] Timestamp { get; set; } 

    [ForeignKey("RecruiterID")] 
    public virtual Members Recruiter { get; set; } 
    [ForeignKey("AuditorID")] 
    public virtual Members Auditor { get; set; } 
} 

基本上我是把外鍵綁在一起吧?

這裏是我收到的錯誤:

Unable to determine the principal end of an association between the types 
'tn.Data.Members' and 'tn.Data.Members'. The principal end of this association 
must be explicitly configured using either the relationship fluent API or data 
annotations. 

我有很多其他表這樣的,但如果我能得到這一個工作,那麼我就能夠解決他們所有。

+0

招聘人員和審計人員都屬於會員類型?這是如何工作的? –

+0

@AlaaMasoud在本網站的前一版本中,我只是在mysql中使用JOIN做到了這一點。但我現在將網站從php遷移到ASP.Net並升級網站。所以基本上這個表格爲社區擁有'會員'。每個「會員」可以有一個「招聘人員」,他顯然也是一個「會員」,但是處於領導型角色。我不必這樣做。我只希望能夠運行1個查詢,並獲取成員的信息,以及他們的招聘人員的一些信息(如UNAME) – SnareChops

回答

2

我會使用這些關係的流暢規範進行conciser,因爲它們有點整齊,所以實際的類純POCO和IMO更容易閱讀。

在另一個說明中,您描述的結構實際上並不是真正可以使用SQL,因爲成員需要成員,這意味着您無法引導您的模型,並且它始終會有循環。

以下是您如何使用流暢配置來做到這一點。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Members>() 
     .HasOptional(m => m.Auditor) 
     .WithMany() 
     .HasForeignKey(p => p.AuditorId); 

    modelBuilder.Entity<Members>() 
     .HasOptional(m => m.Recruiter) 
     .WithMany() 
     .HasForeignKey(p => p.RecruiterId); 
} 

有關如何使用的導航性能與EF看看我的文章在這裏一些細節:http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first

+1

還要注意,您必須更改「AuditorID」和「RecruiterID」的類型''使用'HasOptional()'來調用'int?'屬性。 –

+0

@JeremyTodd是啊這絕對是我應該加入:) –

+1

因此'int?'基本上與SQL中的'int null'相同?我現在正在將此代碼加入代碼中... – SnareChops

2

只需添加到盧克·麥格雷戈的回答,這種情況正在發生,因爲你有兩個自我參照的外鍵在同一個表中,默認情況下,實體框架將跳轉到錯誤的結論,並認爲這意味着它們是相同關係的兩端(即錯誤地假設你的兩個外鍵試圖建立父/子關係) 。這就是爲什麼要問哪一個是委託人,哪一個是委託人。

現在,我認爲沒有辦法通過數據註釋屬性來糾正其誤解,因此您必須使用Luke建議的Fluent API。