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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With