我有一個分貝如下:如何映射2個表並將關係包含在ASP.NET C#Entity-Framework中?
我使用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標識獲取產品。
我該怎麼做?
在此先感謝。
我更新了simpllifed代碼。事實上,我已經這樣做了。 –
有趣的是,這工作。 「ToList()」..謝謝E.J.我有趣地說,因爲我使用它作爲從列表派生的集合...不管怎樣,謝謝。 –
認爲它可能:) –