具有上下文处理的异步方法 [英] Asynchronous method with context dispose
问题描述
我在下面有以下代码:
public Task<Service> GetSomething()
{
using (var myContext = new DbContext())
{
var returnObj = (from rp in myContext.Services1
join op in myContext.Services2 on rp .Id equals op.ServiceId into g
join ep in myContext.Services3 on rp .Id equals ep.ServiceId
from n in g.DefaultIfEmpty()
where rp.Name == code
select rp).FirstOrDefaultAsync();
return returnObj;
}
}
现在这正在工作,我遇到错误:
Now this is working and I am encountering error:
The operation cannot be completed because the DbContext has been disposed.
阅读后,看起来 FirstOrDefaultAsync
是执行延迟,我需要先将其转换为 list
才能使其具体。
After reading, looks like FirstOrDefaultAsync
is a deffered execution and I need to convert it to list
first for it to be concrete.
我要如何转换该查询的结果,因为我尝试了 .ToListAsync()
,但之后没有任何 FirstOrDefault
。
How am I gonna convert the result of this query because I tried .ToListAsync()
but it doesn't have any FirstOrDefault
after it anymore.
推荐答案
在您的情况下,将调用EF6 Async
操作并执行其任务返回到原始呼叫者。然后,立即丢弃 DbContext
而不等待完成。
这是 async / await $ c的不正确用法$ c>功能。
In your case, EF6 Async
operation is called and its task is returned to original caller. Then, DbContext
is immediatelly disposed without waiting for completion.
It is an incorrect usage of async/await
functionality.
在处理上下文之前,您需要等待结果:
You need to await the result before disposing your context:
public async Task<YourEntity> GetYourEntity()
{
using (var myContext = new DbContext())
{
var returnObj = (from rp in myContext.Services1
join op in myContext.Services2 on rp .Id equals op.ServiceId into g
join ep in myContext.Services3 on rp .Id equals ep.ServiceId
from n in g.DefaultIfEmpty()
where rp.Name == code
select rp).FirstOrDefaultAsync();
//return returnObj; // returns Task, wrong!
return await returnObj; // returns result, right!
}
}
这样,它将等待操作完成并然后处置 myContext
。
This way, it will wait for operation to complete and then dispose myContext
.
这篇关于具有上下文处理的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!