We port our Dapper based application to .NET Core and we have a problem with our transaction code.
We use "actions" to execute stuff
public Action<IDbConnection> CreateAction(string statement, object values)
{
return (dbConnection) => dbConnection.Execute(statement, values);
}
And we use methods to execute those actions with
public void Execute(IEnumerable<Action<IDbConnection>> actions)
{
using (IDbConnection connection = OpenConnection())
using (IDbTransaction transaction = connection.BeginTransaction())
{
try
{
foreach (var action in actions)
{
action(transaction.Connection);
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
This works great with .NET Framework and Dapper 1.42, but it fails on .NET Core with Dapper 1.50.2.
System.InvalidOperationException: 'ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.'
If we remove the transaction using it also works fine.
What needs to change to make it work?
Ok, it seems we now have to pass the transaction explicit.
public void Execute(IEnumerable<Action<IDbConnection, IDbTransaction>> actions)
{
using (IDbConnection connection = OpenConnection())
using (IDbTransaction transaction = connection.BeginTransaction())
{
try
{
foreach (var action in actions)
{
action(transaction.Connection, transaction);
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With