在DbContext中使用语句ToListAsync():“ObjectContext disposed”,如何处理?

时间:2014-11-30 14:14:59

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

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

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实例,不能再用于需要连接的操作。”如图所示:

enter image description here

我认为这是因为当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;
}

1 个答案:

答案 0 :(得分:7)

您在using操作完成之前离开ToListAsync范围,因为您没有等待异步任务,这意味着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();
     }
}