Dapper Transaction

Dapper provides different ways to work with transactions. The most common way is to use the BeginTransaction method available on the IDbConnection interface. That will return an instance of IDbTransaction, which you can use with Execute and Query methods to add, remove and modify data in your database tables.

// Open the connection and start a transaction: 
using (var connection = new SqlConnection(connectionString))
{ 
    connection.Open();
	
    using (var tran = connection.BeginTransaction()) 
    { 
        // Execute your queries here
		
        tran.Commit(); //Or rollback 
    }
}

You can also use the TransactionScope class, which provides a much simpler way to deal with transactions:

// Open the connection and start a transaction: 
using (var scope = new TransactionScope()) 
{ 
    // Execute your queries here
	
    scope.Complete(); //Or it will automatically rollback 
}

While using Dapper transaction, i have started getting this error;

"A TransactionScope must be disposed on the same thread that it was created."

Looking around, I figured this out;

In .NET Framework 4.5.1, there is a set of new constructors for TransactionScope that take a TransactionScopeAsyncFlowOption parameter.

According to the MSDN, it enables transaction flow across thread continuations. Here is an example;

using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    await SomeMethodInTheCallStackAsync()
        .ConfigureAwait(false);

    tx.Complete();
}

For complete detail, read this article.

Reference

https://www.learndapper.com/misc/transaction

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect