C# Dapper - How to use transactions with Dapper

Dapper is a micro ORM or a simple object mapper and it integrates smoothly with C# and its SqlConnection. The same applies to Dapper and transactions since Dapper extends the SqlConnection transactions work smoothly with it. Below is an example of running a transaction with two Inserts using Dapper.Contrib:

using var con = new SqlConnection("<Your connectionstring>");
con.Open();
using var transaction = con.BeginTransaction();

var result = con.Insert<MyEntity>(new MyEntity { 
   Text = "This is a text!"}, transaction);
var result2 = con.Insert<MyEntity>(new MyEntity { 
   Text = "This is another text!" }, transaction);
transaction.Commit();

In the above we first create and open a new SqlConnection. We then begin a transaction on the Sql connection and provide this for our SQL statements, which are two inserts. When we are done we commit the transaction. That is all there is to it.

We can test the above by putting an exception between the two inserts:

using var con = new SqlConnection("<Your connectionstring>");
con.Open();
using var transaction = con.BeginTransaction();
var result = con.Insert<MyEntity>(new MyEntity { 
   Text = "This is a text!"}, transaction);
throw new Exception(); //Here
var result2 = con.Insert<MyEntity>(new MyEntity { 
   Text = "This is another text!" }, transaction);
transaction.Commit();

In the above nothing is inserted as an exception is thrown and the transaction is never committed. Had there been no transaction in the above the first Insert would have been inserted and the second not.

That is it

I hope you found this helpful, please leave a comment down below, I read all of them!