dbcontextを含むメソッドを終了する前に、.ToList()を呼び出す必要があります。これにより、データベースが呼び出され、Commentクラスがいっぱいになります。それ以外の場合、そのメソッドの外部で「オブジェクトに含まれるオブジェクトからデータを取得」しようとして、それらがロードされていない場合、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>");
}
}