How to use transactions with dapper.net?

Solution 1:

Here the code snippet:

using System.Transactions;    
....    
using (var transactionScope = new TransactionScope())
{
    DoYourDapperWork();
    transactionScope.Complete();
}

Note that you need to add reference to System.Transactions assembly because it is not referenced by default.

Solution 2:

I preferred to use a more intuitive approach by getting the transaction directly from the connection:

// This called method will get a connection, and open it if it's not yet open.
using (var connection = GetOpenConnection())
using (var transaction = connection.BeginTransaction())
{
    connection.Execute(
        "INSERT INTO data(Foo, Bar) values (@Foo, @Bar);", listOf5000Items, transaction);
    transaction.Commit();
}