1

私は以下のようなデータベースを持っています:

ここに画像の説明を入力

私はEFを使用していて、オブジェクトを取得しようとしています。通常、データベースからPRODUCTエンティティを選択した後、以下のようにPRODUCTエンティティのACCESSLEVELエンティティに到達できます。

選択では、INCLUDEを使用します(注: 以下のコードは問題なく動作します!)

//In a method located in some BL layer
public ProductCollection Load()
{
  ProductCollection  Result = new ProductCollection(); //Derived from List
using (var Context = base.Entities)
            {
                    collection = from ItemProduct in Context.Product
                                     .Include("AccessLevel");

                    return Result.AddRange(collection);
            }
}
//In page load in aspx.cs file
foreach(var product in BL.Load())
{
    Response.Write(product.AccessLevel.Name);
}

ただし、ここでは、以下のことを行うと機能しません!

//In a method located in some BL layer
    public ProductCollection Load()
    {
     ProductCollection  Result = new ProductCollection(); //Derived from List
    using (var Context = base.Entities)
                {

                        collection = from ItemProduct in Context.Product
                                         .Include("AccessLevel")
                                         .Join(Context.Product_Category_Map.Where(c => c.ProductCategoryId == 3),
                                    product => product,
                                    map => map.Product,
                                    (product, map) => product
                               ));
;

                        return Result.AddRange(collection);
                }
    }
    //In page load in aspx.cs file
    foreach(var product in BL.Load())
    {
//I Get Exception here and cannot react the included object
        Response.Write(product.AccessLevel.Name);
    }

例外は次のとおりです。

ObjectContext インスタンスは破棄されており、接続を必要とする操作には使用できなくなりました。

最終的に欲しいのは、指定された ProductCategory Id で製品を取得することです。

どうやってやるの?

前もって感謝します。

4

2 に答える 2

1

コレクションの最後に.ToList()を追加できると思います。

return collection.ToList();

これにより、usingステートメントがコンテキストを閉じた後でも結果を利用できるようになります。これが問題の原因であると私は信じています。

于 2012-10-04T14:47:54.453 に答える
0

私はあなたがこれを置き換える必要があると思います:

using (var Context = base.Entities)

これとともに:

using (var Context = new base.Entities)

詳細については、こちらをご覧ください:エンティティフレームワークコンテキストを初期化する最良の方法は?

于 2012-10-04T14:48:09.467 に答える