【发布时间】: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