2012-10-04 80 views
1

我有一個分貝如下:如何映射2個表並將關係包含在ASP.NET C#Entity-Framework中?

enter image description here

我使用EF並試圖獲取對象。在正常情況下,從數據庫中選擇產品實體後,我能達到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標識獲取產品。

我該怎麼做?

在此先感謝。

回答

1

我想你可以添加一個.ToList()到集合的末尾,即

return collection.ToList(); 

這將結果提供using語句關閉的背景下,我相信這是什麼即使造成你的問題。

+0

我更新了simpllifed代碼。事實上,我已經這樣做了。 –

+0

有趣的是,這工作。 「ToList()」..謝謝E.J.我有趣地說,因爲我使用它作爲從列表派生的集合...不管怎樣,謝謝。 –

+0

認爲它可能:) –

0

我認爲你應該更換此:

using (var Context = base.Entities) 

與此:

using (var Context = new base.Entities) 

如果你想知道更多,到這裏看看:Best way to initialize an entity framework context?

+0

謝謝拉尼爾。我其實在基地裏,我總是得到新的實例。我之所以這麼做,是因爲我在實例化時可能有其他操作,這就是爲什麼我使用base.Entities。但它總是一個新的例子。 –

相關問題