2015-09-09 122 views
0

我在我的項目中有兩個以上的相關表格。 並需要獲取相關對象。EntityFramework 6.如何獲取相關對象?

這裏是我做過什麼:http://pastebin.com/BbkT8zvd

並試圖獲得這樣的:

using (LocalContext _db = new LocalContext()) 
{ 
    var list = _db.Document.ToList(); 
    foreach (var item in list) 
    { 
     Console.WriteLine(item.Name+ ": "); 
     foreach (var item2 in item.Comment) 
     { 
      Console.WriteLine(item2.CommentText); 
     } 
    }  
} 

它沒有返回與文檔相關評論。

試過懶惰,急切和明確的加載方法。

我應該在我的代碼中更正什麼?

回答

2

您可以使用預先加載用於獲取相關的實體,預先加載通過使用包含方法來實現:

_db.Document.Include("Comment").ToList(); 

More info

更新:你並不需要在Comment類初始化Document,你Comment類應該是這樣的:

public class Comment 
{ 
    public int Id { get; set; } 
    public int DocId { get; set; } 
    public string CommentText { get; set; } 
    public virtual Document Document { get; set; } 
} 

Document類:

public class Document 
{ 
    public Document() 
    { 
     this.Comment = new HashSet<Comment>(); 
    } 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Title { get; set; } 
    public virtual ICollection<Comment> Comment { get; set; } 
} 

查詢:

var list = _db.Document.Include("Comment").ToList(); 

在這種情況下,所有相關的評論將被加載。使用你必須要小心這些namings CodeFirst方法時 -

+0

@GertArnold我已經更新了我的答案。 –

+0

在Comment的構造函數中初始化'Document'是解決這個問題的關鍵。它阻止關係修復。另請參閱[本問答](http://stackoverflow.com/q/20757594/861716),我已更新以覆蓋此案例。 –

0

在您的評論類的docId屬性重命名爲DocumentId

LazyLoading設置爲true通常應該做的伎倆。嘗試設置它,還包括在你的電話的導航屬性:

_db.Document.Include("Comment").ToList 

PS:這是使用複數名稱爲表和dbsets

+0

*嘗試懶惰,急切和明確的加載方法。* –

+0

看看我的答案的第一部分 - EF可能無法識別您的外鍵。這就是爲什麼你應該重新命名它或用適當的屬性裝飾它。 – stann1

+0

它正確映射。順便說一下,這不是我的代碼。 –