An Exception occurred in the database while saving changes for context type 'ContextType' Microsoft.Data.SqlClient.SqlException (0x80131904)

Question: How do you solve for Entity Framework Context Error "An Exception occurred in the database while saving changes for context type 'ContextType' Microsoft.Data.SqlClient.SqlException (0x80131904): New transaction is not allowed because there are other threads running in the session"?

Answer: Make sure that you are not mixing Async Calls with None Async Calls. This brings a lot of problems as Async Calls to other API functions could run on a different Thread while Blocking None Async Calls could run on the Main Thread causing confusion in your application. 

1. The better way to solve this error is to create two functions, one for Async and another for None Async, in the Async function make sure you await all calls to other API before proceeding. In the None Async function do just that, you cannot use the "await" keyword in the None Async Blocking calls.

Understand the benefit of using Async Await and when to use Blocking None Async Calls. If your application does not need to Scale for Millions of Users then you might get away with using mostly None Async Await Calls, keep in mind that this will block the UI thread making the User experience a little bit of slowness when the Call is being executed on the Main UI Thread.

2. Another good practice when using Entity Framework Database Context to track and update the Entities in the Database is by Saving the changes in the Database Context from the Controller. If you are using a Service Repository pattern where you have Interfaces and Services consuming the Interfaces, sometimes it is tempting to SaveChanges() right in the ServiceRepository class. However, this might cause this error to happen as every Entity is getting tracked by the Database Context. Entity Framework does this to speed up CRUD (Create, Read, Update and Delete) Operations. Be aware that you can turn off tracking but the repercussion is grim.

- The error is most likely to occur when you are iterating on the Objects in a For Loop or Foreach Loop, this is because EF Core is tracking every object and committing the changes to the Database a For/Foreach Loop might hinder speed and cause the error to occur Plus it is considered bad practice to SaveChanges() to the Database every now and then. The Only time you can save the Changes to the Database in a For Loop is when you find the One Single Entity you want to do operations on then SaveChanges() as soon as possible.

- Hope this helps. Find another article here.
Did you know you could edit this article? Just click on "Edit" below.

Edit this Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

© 2022 - ErnesTech - Privacy