繁体   English   中英

如何映射2个表并在ASP.NET C#实体框架中包含关系?

[英]How to map 2 tables and include the relations in ASP.NET C# Entity-Framework?

我有一个数据库,如下所示:

在此处输入图片说明

我正在使用EF并尝试获取该对象。 在通常情况下,从数据库中选择PRODUCT Entity后,我可以到达PRODUCT Entity的ACCESSLEVEL Entity,如下所示:

在选择时,我使用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获得产品。

我怎样才能做到这一点?

提前致谢。

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

return collection.ToList();

即使using语句关闭了上下文,这也将使结果可用,我相信这是导致您出现问题的原因。

我认为您应该替换为:

using (var Context = base.Entities)

有了这个:

using (var Context = new base.Entities)

如果您想了解更多,请看这里: 初始化实体框架上下文的最佳方法?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM