Database Execution Policies In Entity Framework Core 6

We were developing a database project in .NET 6 using Entity Framework Core. Our back-end database engine was MySql rather than SQL server. It was a remote database. Short operations like single read and write worked fine but suddenly I stuck somewhere and got this horrible error.

Database Execution Policies In Entity Framework Core 6

The error was

“A second operation was started on this context instance before a previous operation was completed. This is usually caused by different threads concurrently using the same instance of DbContext.”

I started the operation again and surprisingly, this time the error was different regardless of the fact that all the inputs I provided were the same.

The error I got this time is:

The configured execution strategy 'MySqlRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.'

Please note that if you are using SQL Server as a database engine, You’ll receive SqlRetryingExecutionStrategy rather than MySqlRetryingExecutionStrategy.

Database Execution Policies In Entity Framework Core 6

I tested the application many times and explored the stack trace in detail and also do a lot of search online but failed to figure out the issue as my app followed all the suggested solution standards.

I started following a thread on github where one important thing was mentioned.

One has to be careful while working with sync and async method. If you are following sync method patterns in your code, better to follow it completely, mean use sync method in all of your codebase. Don’t mix sync calls with async calls in your code.

If you working with async methods in your code it is highly recommended to use the async method with await in all the places in your codebase.

This last line give me some hint to find out the issue so started exploring the code backward. From the position where error or exception was coming while going backward from line to line, there was an async function which has no await before its invocation.

Database Execution Policies In Entity Framework Core 6

As soon as I applied this await prior to this call, both errors are gone.