2012-06-30 96 views
5

我正在實現允許用戶彼此關注的功能。 我有數據庫表:實體框架類問題中的兩個相同類類型

User{UserId, FirstName, LastName etc.} 
Followings{FollowerUserId, FollowingUserId, CreatedOnDate etc.} 

所以我加入EF類:

public class Follow 
    { 
     [Key, Column(Order = 1)] 
     public Guid FollowerUserId { get; set; } 
     [Key, Column(Order = 2)] 
     public Guid FollowUserId { get; set; }   
     public DateTime CreatedOnDate { get; set; } 

     public virtual User Follower { get; set; } 
     public virtual User Following { get; set; } 
    } 

最後兩個虛擬財產職高問題。 當我打電話:

var model = con.Follows.Where(x => x.FollowerUserId == uid); 

我得到以下異常:

Invalid column name 'Following_UserId'. 

的問題可能是一類造成的,因爲兩個用戶對象。任何想法如何解決這個問題?
UPDATE

public class User 
    { 

     public Guid UserId { get; set; } 
     ... 
     public virtual ICollection<Follow> Following { get; set; } 
     public virtual ICollection<Follow> Followers { get; set; } 
    } 
+0

它似乎不適合我把兩個userID和導航屬性,你應該只放其中一個,否則EF不能建立它們之間的連接 – Clueless

+0

你能更好地解釋我不知道如何解決這個問題嗎? – 1110

回答

4

我想原因是,外鍵屬性(FollowerUserIdFollowUserId)和導航性能(FollowerFollowing)不尊重的命名規則,使EF是無法識別第一個屬性作爲外鍵。您可以通過指定顯式使用[ForeignKey]屬性FK性能解決該問題:

public class Follow 
{ 
    [Key, Column(Order = 1), ForeignKey("Follower")] 
    public Guid FollowerUserId { get; set; } 
    [Key, Column(Order = 2), ForeignKey("Following")] 
    public Guid FollowUserId { get; set; }   

    public DateTime CreatedOnDate { get; set; } 

    public virtual User Follower { get; set; } 
    public virtual User Following { get; set; } 
} 

編輯

最小的第二個屬性不尊重的命名慣例,第一個看起來不錯。所以,或者你也可以重新命名第二FK財產FollowUserId到解決這個問題:

public Guid FollowingUserId { get; set; }   

...因爲導航屬性被稱爲Following

編輯2

關於你的更新:您需要添加[InverseProperty]屬性告訴EF其導航性能屬於一起:

public class Follow 
{ 
    [Key, Column(Order = 1), ForeignKey("Follower")] 
    public Guid FollowerUserId { get; set; } 
    [Key, Column(Order = 2), ForeignKey("Following")] 
    public Guid FollowUserId { get; set; }   

    public DateTime CreatedOnDate { get; set; } 

    [InverseProperty("Followers")] // refers to Followers in class User 
    public virtual User Follower { get; set; } 
    [InverseProperty("Following")] // refers to Following in class User 
    public virtual User Following { get; set; } 
} 
+0

謝謝你在下課時解決了我的問題。還有一件事,如果它不是一個問題我也嘗試添加下面的/追隨者的集合到用戶類(我在我的問題更新中添加它),我又一次得到類似的錯誤:無效的列名'User_UserId'。 – 1110

+0

@ 1110:看我的編輯2。 – Slauma

相關問題