“A second operation started on this context” EF core 3.1 concurrency breaking change [duplicate]

这一生的挚爱 提交于 2020-03-25 16:17:23

问题


I'm migrating from netcoreapp 2.1 to 3.1, and I've found a breaking change for EF core 3.1 that I can't resolve.

Previously in 2.1, this worked:

taskList.Add(MethodOne(myRequestObject));
taskList.Add(MethodTwo(myRequestObject));

await Task.WhenAll(taskList);

where both methods only read(never changed) from the db context and look something like this:

private async Task MethodOne(RequestObject myRequestObject)
{
    var entity = await DbContext
    .MyDbSet
    .OrderByDescending(x => x.SomeProperty)
    .FirstOrDefaultAsync(x => x.Id == myRequestObject.Id);

    if (entity != null)
        myRequestObject.SomeRequestProperty = entity.AnotherProperty;
    }
}

In 3.1, even when I'm just reading and not changing the entities, the DB context ConcurrencyDetector thinks it has EnterCriticalSection which causes an exception when the second method tries to await on the DbContext:

InvalidOperationException: A second operation started on this context before a previous operation completed

So, to work around this I replaced await Task.WhenAll(taskList) with the following:

foreach (var task in taskList)
{
    await task;
}

However, this does not work. The same error occurs, as if the second method begins execution without waiting for the first.

For baseline sanity, I also tried the following which does work(but is not an ideal solution for the real code of my app):

await MethodOne(myRequestObject);
await MethodTwo(myRequestObject);

So here are my questions:

  1. Is there a way to continue to tell EF core 3.1 to allow concurrency when I know it is safe.

  2. If not, why the heck is my foreach workaround not working?

来源:https://stackoverflow.com/questions/60569523/a-second-operation-started-on-this-context-ef-core-3-1-concurrency-breaking-ch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!