上下文释放的异步方法

6
我有以下代码:

下面是代码:

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

哪一行代码引发了异常?您已启用延迟加载吗?如果您已执行@Yeldar Kurmangaliyev建议的更改,仍然出现已释放异常,则我只能认为延迟加载是原因。 - Alaa Masoud
1个回答

5
在您的情况下,EF6的异步操作被调用并将其任务返回给原始调用者。然后,DbContext立即被处理而不等待完成。
这是一种错误使用异步/等待功能的方式。
在处理上下文之前,您需要等待结果:
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


将您的方法标记为异步,如此编写:public async Task<Service> GetSomething() - IvanJazz
随着C# 8的到来,Using Declaration也随之而来,这使我们可以使用以下代码:using var myContext = new DbContext()。更多信息请参见https://www.syncfusion.com/blogs/post/csharp-8-0-using-declaration.aspx。 - Esset

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接