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.