尽管在using语句中调用了ToList, DbContext还是被处理了

本文关键字:DbContext 处理 ToList using 语句 调用 | 更新日期: 2023-09-27 18:14:14

我看到一个操作无法完成,因为DbContext已被处置。异常消息,即使代码通过返回List来使用急切加载。我在EntityRepository类中有以下代码:

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

这是由web服务类调用的:

private static EntityRepository EntityRepositoryStatic = new EntityRepository();
[WebMethod]
public List<Entity> GetEntityByProperty(string property)
{
    return EntityRepositoryStatic.GetEntityByProperty(property);
}
EntityRepository继承自Repository基类,该基类实现了IDisposable(处置上下文),并使用以下代码返回上下文实例:
private AppDbContext appDbContext;
public AppDbContext GetContext()
{
    if (appDbContext == null)
    {
        appDbContext = new AppDbContext();
    }
    return appDbContext;
}

在调用存储库中的appDbContext的那一行抛出异常。我错过了什么明显的东西吗?

这是一个很大的遗留代码库,因此我们只是试图用调用存储库类来代替对web服务中上下文的内联调用。

尽管在using语句中调用了ToList, DbContext还是被处理了

第一次调用GetContext()时创建一个新的上下文,然后返回它,然后使用并处理它。然后,对GetContext()的下一次调用返回原始的、已经被处置的上下文,您将得到一个错误。如果你想重复使用它,你不能处理它;如果你想在完成后处理它,你不能重复使用它。