简体   繁体   English

尽管在using语句中调用ToList,但DbContext已被处置

[英]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. 我看到一个操作无法完成,因为已经处理了DbContext。 exception message even though the code is using eager loading by returning List<T> . 即使代码通过返回List <T>使用急切加载,也会出现异常消息。 I have the following code in an EntityRepository class: 我在EntityRepository类中有以下代码:

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: 这又是从Web服务类中调用的:

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: EntityRepository继承自Repository基类,该基类实现IDisposable (以处理上下文),并具有以下代码以返回上下文的实例:

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. 在对存储库中的appDbContext进行调用的行上引发了异常。 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. 这是一个庞大的遗留代码库,因此我们只是尝试将对Web服务中的上下文的内联调用替换为对存储库类的调用。

The first time you call GetContext() you create a new context, then you return it, then it's used and disposed of. 首次调用GetContext()您将创建一个新上下文,然后将其返回,然后将其使用和处置。 Then the next call to GetContext() returns the original, already disposed, context, and you get an error. 然后,对GetContext()的下一次调用将返回已处置的原始上下文,并且您将收到错误。 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. 如果您想在处理后将其丢弃,则无法重复使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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