Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper, .NET Core and Transactions fail

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?

like image 930
Benjamin Abt Avatar asked Feb 05 '23 15:02

Benjamin Abt


1 Answers

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;
            }
        }
    }
like image 124
Benjamin Abt Avatar answered Feb 23 '23 03:02

Benjamin Abt