SqlException: New transaction is not allowed because there are other threads running in the session

Question: How do you resolve the error that says "SqlException: New transaction is not allowed because there are other threads running in the session" in Asp.Net 6 Application?


Please Login to see the rest of the answer

Answer: When you see this error it is most likely that you have registered the Database or Database Context as a Singleton in the Startup.cs class. If this is the case, starting another Database transaction is not allowed because the Application can only use one Open Connection to the Database. A second thread to the database would throw an exception.

In order to solve this error is to look at your requirement, was there a reason why you registered the Database Context in the Dependency Injection (DI) as a Singleton if yes then it is worth knowing how to establish a connection to the Database without throwing an error.

Another way to resolve this error is to take a look at where another connection is getting instantiated. It is the best idea to add objects to the Database Change Tracker then when it comes time to save changes to the Database to only call _context.SaveChanges() once. The problem might be that you are calling _context.SaveChanges() every time you add an Item to the Database Context.



Write an 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