2

I am trying to solve this problem and did read content regarding this error but was unable to figure out a solution. I am building a winforms application using Entity framework for a simple Products Categories scenario. Here is a snapshot of my model. Edmx

The code in ProductService class that retrieves all the products is

public static List<Product> GetAllProducts()
{
    List<Product> products = new List<Product>();
    using (var entity = new SUIMSEntities1())
    {
        products = (from p in entity.Products
                    select p).ToList();
        return products;
    }            
}

Code in the Products code behind is

List<Product> prods=ProductServices.GetAllProducts();
dgvProducts.DataSource = prods;

When I try to load the Products in datagridview, the following error is shown: enter image description here

Could you please tell me what is causing the problem?

Edit: The Include did the trick and in this specific scenario I changed the GetAllProducts() as below

        public static List<Product> GetAllProducts()
        {
            using (var entity = new SUIMSEntities1())
            {
                List<Product> products = entity.Products.Include("Category").ToList();
                return products;                
            }            
        }
1
  • 2
    In SO it is customary to post code and error messages as text, not screengrabs of text. Commented Aug 9, 2012 at 23:26

2 Answers 2

4

By default, entity framework (EF) will lazy load your Category object set. Because your Category object set is lazy loaded, when some other code later on references a Category, EF will try to load the set. However, at this point, your context has been disposed, resulting in the error you are seeing.

What you need to do is force the context to eagerly load your Category entity set like so:

public static List<Product> GetAllProducts()
{
    List<Product> products = new List<Product>();
    using (var entity = new SUIMSEntities1())
    {
        entity.Include("Category");  //force eager loading of Category
        products = (from p in entity.Products
                    select p).ToList();
        return products;
    }            
}
Sign up to request clarification or add additional context in comments.

2 Comments

Could you edit your answer to show what you're describing? Show exactly where one would use the .Include.
I've added some clarification to my answer.
2

Although you are returning a List<Product>, it would appear that accessing the Category will cause a database access. The problem is that you've already disposed of the context necessary to access the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.