2012-11-15 59 views
0

所以我有2個表CommentsStudents。每一個評論有一個學生: Comment.StudentIdASP.NET - SQL - 檢索'包含'對象

我使用POCO生成的類,它似乎給我的評論類中整個Student對象時,我進行查詢,像這樣:

var query = 
    from comment in context.Comments 
    where comment.StudentId == properId 
    orderby comment.Created 
    select comment; 

所以我可以訪問像這樣comment.Student.Name

但是學生的屬性,當我複製的結果(query.ToList()的方法外使用,它給了我一個錯誤說的ObjectContext的實例被佈置。

如何從包含在對象中的對象檢索數據?

回答

2

添加.INCLUDE .ToList之前(「學生」)()

+0

IOrderedQueryable似乎並不具備該功能 – TheAJ

+1

從context.Comments.Include評論( 「學生」) –

1

記住,LINQ的使用IEnumerable,直到您嘗試遍歷結果會推遲查詢的執行(你會通過調用.ToList())。正如你所說的,如果你打電話給.ToList()「在方法之外」,那麼你可能會處理上下文,這意味着查詢對象不再可行。

一個快速和骯髒的黑客是確保你處置上下文的前一次執行查詢:

var query = 
    (from comment in context.Comments 
    where comment.StudentId == properId 
    orderby comment.Created 
    select comment).ToList(); 
1

你必須調用.ToList()退出包含您的DbContext的方法之前。這將調用數據庫並填寫您的評論類。否則,當您嘗試在該方法之外「從包含在對象中的對象中檢索數據」並且它們尚未加載時,您會看到DbContext已被處置。這是因爲EF試圖爲這些項目重新「加載」或「調用數據庫」。當然,由於您現在不在包含上下文的方法之外,因此EF無法加載它們。您應該閱讀EF默認打開的「延遲加載」功能。

您可能希望創建一個方法,它只返回完全加載的Comment對象。事情是這樣的:

public class YourDbAccessClass { 
    public IEnumerable<Comment> GetCommentsByStudentId(int id) { 
     using (YourContextClass context = new YourContextClass()) { 
      // Eager load Student with the .Include() method. 
      var query = from comment in context.Comments.Include("Student") 
         where comment.StudentId == id 
         orderby comment.Created 
         select comment; 

      return query.ToList(); 
     } 
    } 
} 

然後在您的調用代碼:

protected void ...some method on your view or asp page { 
    YourDbAccessClass db = new YourDbAccessClass(); 
    var comments = db.GetCommentsByStudentId(yourIdVariableHere); 

    // Now you can loop through those items without dbcontext. 
    // Response.Write is probably a bad example, but you probably get the gist here. 
    foreach(var comment in comments) { 
     Response.Write("<li>" + comment.Student.Name + "</li>"); 
    } 
}