带有上下文 dispose 的异步方法

Ger*_*les 6 c# asynchronous entity-framework

我有以下代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这正在工作,但我遇到了错误:

The operation cannot be completed because the DbContext has been disposed.
Run Code Online (Sandbox Code Playgroud)

读完后,看起来像是FirstOrDefaultAsync一个延迟执行,我需要将其转换为list第一个执行才能使其具体化。

我该如何转换这个查询的结果,因为我尝试过,但后面.ToListAsync()没有任何结果了。FirstOrDefault

Yel*_*yev 5

在您的情况下,将调用 EF6Async操作并将其任务返回给原始调用者。然后,DbContext立即处理,无需等待完成。
这是功能的错误使用async/await

在处理上下文之前,您需要等待结果:

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!
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,它将等待操作完成然后进行处理myContext