Dapper, .NET Core and transactions error
We are porting our Dapper based application to .NET Core and we have a problem with our transaction code.
We use "actions" to take actions
public Action<IDbConnection> CreateAction(string statement, object values)
{
return (dbConnection) => dbConnection.Execute(statement, values);
}
And we use methods to do these things 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 fine 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 delete the transaction using it, it works great too.
What needs to be changed to make it work?
+3
source to share
1 answer
Ok, now we need to pass the transaction explicitly.
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;
}
}
}
+6
source to share