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

entity framework a second operation started on this context before a previous
entity framework core dbcontext thread safe
dbcontextoptions connection string
ef core parallel operations
dbcontextoptionsbuilder
servicelifetime.transient dbcontext
a second operation started on dbcontext
any instance members are not guaranteed to be thread safe.

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.

A second operation started on this context , Entity Framework Core: A second operation started on this context before a previous operation completed. Update entity error: A second operation started on this context before a previous operation completed Hot Network Questions What are examples of (collections of) papers which "close" a field?


DbContext is not thread-safe. You should create a new context (rather then re-using the same _db instance for each database operation. This is a best-practice even for single-threaded processes.

Side note - that's why when you wait for each task it "works" - because you are no longer accessing your context from multiple threads.

EF Core, But this throwing the below error. A second operation started on this context before a previous operation completed. Any instance members areĀ  An unhandled exception occurred while processing the request. InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe. Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() ForumQueryManager:


I think you are missing to commit the transaction at the end....dbContextTransaction.Commit() after SaveChangesAsync() should do the trick.

A second operation started on this context before a previous , DBContext Error: A second operation started on this context before a previous operation completed. Issue Description. Entity Framework Core runtime gives below error,. A second Update Startup.cs as below,. services. AndriySvyryd changed the title Migration 2.0 to 2.1 : A second operation started on this context before a previous operation completed Improve message for 'A second operation started on this context before a previous operation completed' Sep 26, 2018


Improve message for 'A second operation started on this context , Net Core 2.0 to 2.1 all is fine but when I update my Microsoft. The solution use EntityFrameworkCore & EntityFrameworkCore.SqlServer 2.0.3 it's work ajcvickers added regression type-bug labels on Jul 2, 2018 fail: A second operation started on this context before a previous operation completed. Entity Framework Core runtime gives below error, A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however, instance members are not guaranteed to be thread-safe. I observed this issue in ASP.NET Core 3.1 version recently.


InvalidOperationException: A second operation started on this , operation started on this context before a previous operation completed #1023 MySql 3.1.1 But now I am getting the following error Entity Framework Core does not support multiple parallel operations being run on theĀ  ERROR 2018-05-02 20:09:15,176 [7 ] lers.Filters.AbpExceptionFilterAttribute - System.NotSupportedException: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context.


Entity Framework error: A second operation started on this context , started on this context before a previous operation completed Because the error is based on, effectively, a race condition, your mileage may vary I set-up a console app accessing Entity Framework; in this case, EF Core. System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.