【问题标题】:How to map 2 tables and include the relations in ASP.NET C# Entity-Framework?如何映射 2 个表并在 ASP.NET C# Entity-Framework 中包含关系?
【发布时间】:2012-10-04 14:43:17
【问题描述】:

我有一个数据库如下:

我正在使用 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 获取产品。

我该怎么做?

提前致谢。

【问题讨论】:

    标签: c# asp.net entity-framework-4 relationships


    【解决方案1】:

    我认为您可以将 .ToList() 添加到集合的末尾,即

    return collection.ToList();
    

    即使在 using 语句关闭上下文后,这也将使结果可用,我认为这是导致您的问题的原因。

    【讨论】:

    • 我更新了简化的代码。事实上,我已经这样做了。
    • 有趣的是,这很有效。 “ToList()” .. 谢谢 E.J.我说的很有趣,因为我将它用作从 List 派生的集合......无论如何,谢谢。
    【解决方案2】:

    我认为你应该替换这个:

    using (var Context = base.Entities)
    

    用这个:

    using (var Context = new base.Entities)
    

    如果您想了解更多,请看这里:Best way to initialize an entity framework context?

    【讨论】:

    • 谢谢拉尼尔。事实上,我在基地里总是得到新的实例。我这样做的原因可能是在实例化过程中还有其他操作,这就是我使用 base.Entities 的原因。但它总是一个新的实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 2019-09-13
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多