How to use transactions with dapper.net?

后端 未结 5 756
夕颜
夕颜 2020-12-12 15:55

I would like to run multiple insert statements on multiple tables. I am using dapper.net. I don\'t see any way to handle transactions with dapper.net.

Please share y

5条回答
  •  旧时难觅i
    2020-12-12 16:36

    Daniel's answer worked as expected for me. For completeness, here's a snippet that demonstrates commit and rollback using a transaction scope and dapper:

    using System.Transactions;
        // _sqlConnection has been opened elsewhere in preceeding code 
        using (var transactionScope = new TransactionScope())
        {
            try
            {
                long result = _sqlConnection.ExecuteScalar(sqlString, new {Param1 = 1, Param2 = "string"});
    
                transactionScope.Complete();
            }
            catch (Exception exception)
            {
                // Logger initialized elsewhere in code
                _logger.Error(exception, $"Error encountered whilst executing  SQL: {sqlString}, Message: {exception.Message}")
    
                // re-throw to let the caller know
                throw;
            }
        } // This is where Dispose is called 
    

提交回复
热议问题