【问题标题】:ToListAsync() in a DbContext using statement : "The ObjectContext disposed", How to deal?DbContext 中的 ToListAsync() using 语句:“已处理的 ObjectContext”,如何处理?
【发布时间】:2014-11-30 14:14:59
【问题描述】:

我正在尝试使用 .ToListAsync() 在 DbContext 的 using 语句中获取 linq 查询结果,代码:

private async Task<List<String>> GetEntiteesAsync()
{
     Task<List<String>> returnValue;

     using (var entities = new REPORTEntities())
     {
          returnValue = (from user in entities.USERs
                         group user by user.entite into g
                               select g.Key).ToListAsync();
     }

     return await returnValue;
}

运行时我得到“ObjectContext 实例已被释放,不能再用于需要连接的操作。”如图:

我想这是由于在 returnValue 对象仍然作为 List 异步接收对象时释放了 Context 造成的,是否有一种解决方法可以在保留 using 语句的同时避免此错误,或者我应该去通过这样做:

private async Task<List<String>> GetEntiteesAsync()
{
     Task<List<String>> returnValue;

     var entities = new REPORTEntities()

     returnValue = (from user in entities.USERs
                    group user by user.entite into g
                    select g.Key).ToListAsync();

     return await returnValue;
}

【问题讨论】:

    标签: c# linq entity-framework asynchronous async-await


    【解决方案1】:

    您将在 ToListAsync 操作完成之前离开 using 范围,因为您没有等待异步任务,这意味着 entities 被处置得太快(因此对象处置异常)。

    您应该在作用域内返回结果,async-await 机制将确保在操作异步完成后调用Dispose

    private async Task<List<String>> GetEntiteesAsync()
    {
         using (var entities = new REPORTEntities())
         {
              return await (from user in entities.USERs
                             group user by user.entite into g
                                   select g.Key).ToListAsync();
         }
    }
    

    【讨论】:

    • 哎呀,我瞎了!从一开始就应该那样做,不知道我为什么把它复杂化了,谢谢先生!
    • @AymenDaoudi 当然可以。
    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 2016-10-24
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多