Search code examples
c#asp.netentity-framework-4relationships

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


I have a db as below:

enter image description here

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.


Solution

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

    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.