|
TransactionScope uses thread-local storage under the covers and as far as I am aware this will not work reliably with task-based async because when the code continues executing it may do so on a different thread. This is not specific to the EF implementation
of async but rather a general problem with Task-based async.
Unfortunately, the EF team doesn't have the ability to update TransactionScope and it doesn't seem like it will be fixed anytime soon. We have been doing thinking around how to make a nice experience for transactions with EF without using TransactionScope
but we don't have anything concrete to share yet. We also have a few bugs around how transactions and DbContext.Database.Connection work.
For now, you can do something like this as a workaround:
using (var context = new MyContext())
{
var connection = ((IObjectContextAdapter)context).ObjectContext.Connection;
connection.Open();
using (var transaction = connection.BeginTransaction())
{
// Some async stuff
transaction.Commit();
}
connection.Close();
}
|