Entity Framework Error : The ObjectContext instanc

2019-07-23 19:04发布

问题:

I am using Entity Framework with a business Later, DAL and a base Interface. I am inheriting the IDispose interface in my repository, I am getting the following error trying to get this list back. most of the examples I have come across suggest using IEnumerable and add .ToList() for the query and I have already as seen below. How can I get around this? This is working in other places where I have similar multiple related entity queries, I dont understand why im getting the error here? If someone can point out with an example in code how to fix this that would be great.

public IEnumerable<Orders> GetOrdersByCustomer(int customer_id)
{
    IEnumerable<Orders> ordersList = context.Employees
        .Include("Orders")
        .Include("Customers")
        .Where(c => c.Customers.customer_id == customer_id)
        .ToList();

    return ordersList;
}

回答1:

I found the reason it wasnt working actually I had to do something like

public IEnumerable<Orders> GetOrdersByCustomer(int customer_id)
{              
    IEnumerable<Orders> ordersList = context.Employees
        .Include("Customers")
        .Include("Customers.Orders")
        .Where(c => c.Customers.customer_id == customer_id)
        .ToList();          
    return ordersList;
} 


回答2:

It sounds like whatever class you have which "owns" the context has disposed of it, and a subsequent call in the line IEnumerable<Orders> ordersList = context.Employees.Include is throwing an error.