2013-02-21 106 views
0

比方說,我有3個表:EF代碼第一個外鍵定義/左連接/導航屬性?

[Table("Comments")] 
public class Comment { 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    [ForeignKey("Users")] 
    public int UserId { get; set; } 
    public virtual Users Users { get; set; } 
    public string Text { get; set; } 
} 

[Table("Users")] 
public class Users { 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    public string UserName { get; set; } 
} 

[Table("CommentAgree")] 
public class CommentAgree { 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    public int CommentId { get; set; } 
    public int UserId { get; set; } 
} 

用戶發表評論,而其他用戶可以「同意」與評論,有點像Facebook的「喜歡」系統。我使用的λ爲我的查詢,我可以這樣做:

var query = db.Comments.Select(c => new { 
      c.Id, 
      c.Users.UserName, 
      c.Text 
}); 

我怎樣才能創建一個連接到CommentAgree上Comment.Id = CommentAgree.CommentId?我可以寫在LAMBDA的加入,但我需要它是一個左連接因爲沒有人可以與評論表示贊同,但我還是希望它顯示。

我想這樣做的正確的方式,所以我打開的建議是否可以通過外鍵,拉姆達連接,導航性能...還是其他什麼東西做的?

這可能嗎?

感謝

回答

1

最好的辦法可能是使用實體框架的功能和使用LINQ進行聯接只是相關數據創建的導航性能,而不是明確的。

如果你的類型是形只爲數據訪問的目的,然後添加導航屬性的關係的兩端可能是一個好主意,與你已經有外鍵屬性一起。

Comment集合導航屬性應該實現ICollection(例如List<CommentAgree>),你將有Comment種類對CommentAgree類型的引用導航屬性。

這樣,你會在你的映射定義的關係,無論是使用數據批註或(最好)流利的API。

要加載相關數據,您可以使用延遲加載或急切加載(使用擴展方法Include),也可以使用來自實體的條目信息的顯式加載。

+0

嗯好的,我添加了一個公開名單(我忘了說我有一個CommentAgree FK評論)。然後在我的lambda中,我可以做c.CommentAgrees.Count(),這給了我正是我想要的!我認爲,排序我,但我會考慮正確映射它,因爲我沒有這樣做之前,將檢查出流利的API。謝謝你的幫助 – Rodders 2013-02-21 15:23:14