Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework and Web API ObjectDisposedException

I have a data layer that uses Entity Framework 5 to connects to Sql Server. I also have a LINQ query that gets some data. This query fails when used with Web API. I get the ObjectDisposedException. Here's the query:

using (MyContext container = new myContext())
{
    return container.Sales
                    .Include("Products")
                    .Where(s => s.Id == id)
                    .FirstOrDefault();
}

The data layer is a dll, exposed by a business layer, also a dll, which is called by a web api controller. I had assumed that the JSON serializer was lazy loading the includes but none of my fixes have worked. Any ideas? I will update the question as need be if info is missing.

Here is the business layer call to the data layer:

public Sale GetSale(int id)
{
    SaleRepository s = new SaleRepository();
    return s.GetSale(id);
}

And finally the web api call to the business layer:

public Sale GetSale(int id)
{
    SaleManager s = new SaleManager();
    return s.GetSale(id);
}

Here is the exception:

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

like image 932
CYAD Avatar asked Apr 15 '26 22:04

CYAD


2 Answers

This happens because lazy loading is being performed after your DbContext has been disposed.

To resolve the issue you can disable lazy loading by doing this:

container.Configuration.LazyLoadingEnabled = false;
like image 198
Peter Hansen Avatar answered Apr 17 '26 11:04

Peter Hansen


There must be an issue with lazy loading and the include not working as expected - try changing your code to select the actual object and the included entities.

using (MyContext container = new myContext())
{
    var result = container
        .Sales
        .Include("Products")
        .Where(s => s.Id == id)
        .FirstOrDefault();
    result.Products.ToList();
    return result;
}
like image 41
qujck Avatar answered Apr 17 '26 12:04

qujck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!