0

I am seeing a The operation cannot be completed because the DbContext has been disposed. exception message even though the code is using eager loading by returning List<T>. I have the following code in an EntityRepository class:

public List<Entity> GetEntityByProperty(string property)
{
    using (AppDbContext appDbContext = GetContext())
    {
        List<Entity> entities = appDbContext.Entities
            .Where(e => e.Property == property)
            .ToList();

        return entities;
    }
}

This is in turn being called from a web service class:

private static EntityRepository EntityRepositoryStatic = new EntityRepository();

[WebMethod]
public List<Entity> GetEntityByProperty(string property)
{
    return EntityRepositoryStatic.GetEntityByProperty(property);
}

The EntityRepository inherits from a Repository base class which implements IDisposable (to dispose the context) and has this code to return an instance of the context:

private AppDbContext appDbContext;

public AppDbContext GetContext()
{
    if (appDbContext == null)
    {
        appDbContext = new AppDbContext();
    }

    return appDbContext;
}

The exception is thrown on the line making the call to appDbContext in the repository. Am I missing something obvious?

This is a large legacy codebase therefore we are simply trying to replace inline calls to the context in the web service with calls to the repository classes instead.

BWHazel
  • 1,434
  • 1
  • 17
  • 28
  • You didn't use the *eager loading* here. After calling this method, You cannot load the related entity lazily because the db is disposed and so the Eager Loading would be a better choice here. Check here http://stackoverflow.com/a/34628138/2946329 – Salah Akbari Oct 20 '16 at 15:21
  • Or maybe this will be helpful also:http://stackoverflow.com/questions/36961249/using-include-doesnt-change-the-behavior – Salah Akbari Oct 20 '16 at 15:23
  • Sorry - misprint in `GetContext()` - should be `appDbContext` - I'll update it now. – BWHazel Oct 20 '16 at 15:29
  • @BWHazel Well you need to use `Include` to use *eager loading* and get rid of this error. Check the examples I linked to know how and explanation. – Salah Akbari Oct 20 '16 at 15:33

1 Answers1

1

The first time you call GetContext() you create a new context, then you return it, then it's used and disposed of. Then the next call to GetContext() returns the original, already disposed, context, and you get an error. If you want to re-use it, you can't dispose it; if you want to dispose of it when done, you can't re-use it.

Servy
  • 193,745
  • 23
  • 295
  • 406
  • OP please review this solution it is correct, since you are using a Repository beyond a call and internally disposing the shared context in first call, thus an exception. Ideally Context shall get disposed on disposing the EntityRepository object, not in every call. – Mrinal Kamboj Oct 20 '16 at 17:37