简体   繁体   中英

DbContext has been disposed despite calling ToList within using statement

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM