简体   繁体   中英

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

I have a db as below:

在此处输入图片说明

I am using EF and trying to get the object. Under normal circumstances after selecting PRODUCT Entity from database I can reach ACCESSLEVEL Entity of PRODUCT Entity like below:

In selecting, I use INCLUDE (NOTE: the code below works fine!)

//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);
}

However, in here when I do the thing below it does NOT work!

//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);
    }

The Exception is:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

What I finally want is to get products by the given ProductCategory Id.

How can I do that?

Thanks in advance.

I think you could add a .ToList() to the end of the collection, ie

return collection.ToList();

This will make the results available even after the using statement closes the context, which I believe is what is causing your problem.

I think you should replace this:

using (var Context = base.Entities)

with this:

using (var Context = new base.Entities)

If you want to know more, take a look here: Best way to initialize an entity framework context?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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