Update entity error: A second operation started on this context before a previous operation completed

c# entity-framework entity-framework-core

Question

When I update the entity, I got the error in the controller

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

Code:

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

The method is

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

To explain the code, basically I have three tables. _db.MyProject, _db.MyMap and _db.MapProjectLink. The first two tables are many to many; and the third table links them together. I want to save the updated value to the two tables: _db.MyProject and _db.MapProjectLink.

By the way I don't use dependency injection at this moment. I guess that maybe the for loop causes the problem.

The error is

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.

1
3
10/9/2019 3:49:40 AM

Popular Answer

It's turns out I have to put everything associated with _db into Task.Run. Then Wait. Which means wait the task finish then continue to the next flow.

1
10/9/2019 11:38:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow