c# - 更新实体错误 : A second operation started on this context before a previous operation completed

标签 c# entity-framework entity-framework-core

当我更新实体时,我在 Controller 中收到错误

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

代码:

public class MyController: Controller
{
   private readonly DbContext _db = new DbContext();

方法是

[HttpPatch]
[Route("MyRoute")]
public async Task<ActionResult> UpdateMyCase([Required][FromBody]MyProject body)
{
    using(var dbContextTransaction = _db.Database.BeginTransaction())
    {
        _db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        var p = (from a in _db.MyProject
                 where a.Id == body.Id
                 select a).FirstOrDefault();
        p.Name = "new Name";
        p.Score = "new score";

        // ....
        var m = _db.MyProjectLink.Where(x => x.Id == p.Id);

        for(var key in m)
        {
            if(m.Any(x => x.Id != "something"))
            {
                var link = new MapProjectLink();
                link.MapId = "some id dynamic generated";
                link.Id = body.Id;
                link.Tool = key.tool;
                _db.MapProjectLink.Add(link);
            }
        }

        await _db.SaveChangesAsync();
        return OK(p);
    }
}

为了解释代码,基本上我有三个表。 _db.MyProject、_db.MyMap_db.MapProjectLink。前两个表是多对多的;第三个表将它们链接在一起。我想将更新后的值保存到两个表中:_db.MyProject_db.MapProjectLink

顺便说一句,我现在不使用依赖注入(inject)。我想可能是 for 循环导致了问题。

错误是

An exception occurred in the database while saving changes for context type 'MapProjectLink'. System.InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

最佳答案

事实证明,我必须将与 _db 关联的所有内容放入 Task.Run 中。然后等待。这意味着等待任务完成然后继续下一个流程。

关于c# - 更新实体错误 : A second operation started on this context before a previous operation completed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295759/

相关文章:

c# - Entity Framework Core 词汇比较

c# - Web 浏览器控件导航错误

C# 如何从拉伸(stretch)位图/图片框获取像素

c# - WinForms - 为什么每次我在 Visual Studio 中打开 C# 窗体时都会在其中运行 SQL?

c# - LINQ to Entities 无法识别方法 'System.Web.Mvc.FileResult'

c# - JsonPatchDocument 到复杂的 Entity Framework 跟踪对象

c# - 如何通过电子邮件发送 pdf 格式的 Crystal 报告

c# - Entity Framework MySQL DbContext 无法连接

entity-framework-core - Entity Framework 核心继承创建子表

c# - 两个 LINQ 语句对应一个可等待的 LINQ 数据库查询(优化)