0

だから私は2つのテーブルCommentsStudents. すべてのコメントには生徒がいます: Comment.StudentId

POCO で生成されたクラスを使用しています。次のようなクエリを作成すると、コメント クラス内の Student オブジェクト全体が得られるようです。

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

だから私はそのように学生のプロパティにアクセスできますcomment.Student.Name

ただし、結果をコピーすると (query.ToList()メソッドの外部で使用するために、 ObjectContext インスタンスが破棄されたというエラーが表示されます。

オブジェクトに含まれるオブジェクトからデータを取得するにはどうすればよいですか?

4

3 に答える 3

2

.ToList()の前に.Include( "Student")を追加します

于 2012-11-15T02:29:27.910 に答える
1

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>");
    }
}
于 2012-11-15T03:20:49.623 に答える
1

Linqはを使用することを忘れないでくださいIEnumerable。これは、結果を反復処理しようとするまで(を呼び出す場合と同様に)、クエリの実行を延期します.ToList()。あなたが述べたように「メソッドの外」を呼び出している場合.ToList()、コンテキストを破棄している可能性があります。これは、クエリオブジェクトが実行できなくなったことを意味します。

迅速で汚いハックは、コンテキストを破棄する前に、必ずクエリを1回実行することです。

var query =
    (from comment in context.Comments
    where comment.StudentId == properId
    orderby comment.Created
    select comment).ToList();
于 2012-11-15T02:37:08.600 に答える