Update entity error: A second operation started on this context before a previous operation completed
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.
Comments
- I feel like I read something about not declaring transactions for EF because it handles that under the hood itself, I'll see If i can find something on this.
- This may be a duplicate: stackoverflow.com/questions/48767910/…
- I read that but no big help for my specific case.
- does
await _db.SaveChangesAsync();
utilize multithreading to make database writes? Could that be why its concerned about thread safe? - while
using(var dbContextTransaction = _db.Database.BeginTransaction())
should you still use the async context save? - That's one way to fix it - see my answer for another.
- I thought about it. But just don't know how to wrap it in code. Notice, I have
private n DbContext _db = new DbContext();
at the beginning. - Just copy that to the spots where you use the context (and wrap it in a
using
so it is disposed) :using (DbContext db = new DbContext()) {
. Yes it's repetitive but it's the right way to use it. - Why? Can you add more details please?
- @devendra may be onto something, docs.microsoft.com/en-us/ef/ef6/saving/transactions