Microsoft.EntityFrameworkCore.Database.Transaction[20205] An error occurred using a transaction.


What is Entity Framework and what is it used for?

Entity Framework is an ORM meaning it is an Object Relational Mapper, It is an Open Source Framework developed by Microsoft. Software Developers use Entity Framework (short for EF Core) in their Software Architecture to map Database Tables to Classes in the Application. 

It makes querying and tracking Objects mapped to the Database Tables very easy, it abstracts all the complexities that come with memory management so Developers don't have to deal with it. Well-known websites like StackOverflow.com have mentioned using Entity Framework for their Data Layer.

Error when working with Entity Framework core: Microsoft.EntityFrameworkCore.Database.Transaction[20205] An error occurred using a transaction. System.Data.SqlClient.SqlException (0x80131904): The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

[Description]: The error described above sometimes happens when you have an Asynchronous code executing inside the function that is not Asynchrouse. Meaning, if the function executes Async Code or returns a Task, it is considered a bad practice to execute or call functions that are none-async inside the Async Function.


Login to See the Rest of the Answer

Answer:
If you are saving your changes using _context.SaveChangesAsync() then you need to change to _context.SaveChanges().

The reason why the error happens is that the transaction is run Asynchronously. When you do _context.SaveChanges() or chain the function like _context.[YourDataModel].Add([YourObject]).Context.SaveChanges(); The transaction happens in one commit and the Database connection does not close and reopens to save the changes.

[Note]: Remember that when you use SaveChangesAsync() you await the result, otherwise the Operation will run in the Background or rather on a different thread. This will lock the DatabaseContext and other operations requiring to use of the Database Context would then throw.





Kasiaric said:

Thanks a lot. I was actually using SavechangesAsync() instead of SaveChanges().

Posted On: February 25, 2020 6:46:44 AM

For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]