具有上下文配置的异步方法

时间:2017-07-12 03:26:13

标签: c# entity-framework asynchronous

我在下面有以下代码:

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;
    }
}

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

The operation cannot be completed because the DbContext has been disposed.

阅读之后,看起来FirstOrDefaultAsync是一个被拒绝的执行,我需要首先将其转换为list才能具体。

我将如何转换此查询的结果,因为我尝试.ToListAsync()但它之后没有任何FirstOrDefault

1 个答案:

答案 0 :(得分:1)

在您的情况下,调用EF6 Async操作并将其任务返回给原始调用者。然后,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!
  }
}

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