Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper. IDbConnection and IDbTransaction

How should I use an IDbConnection and an IDbTransaction with Dapper?

At the moment I am using only a IDbConnection. Something as follows:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{
    connection.Execute(@"insert Roles(Name) values (@name)", new { name = "Role" }); 
}

But sometimes I need to send 2 commands? Should I use BeginTransation and EndTransaction?

like image 201
Miguel Moura Avatar asked Dec 09 '22 01:12

Miguel Moura


1 Answers

Yes, if you need two separate commands to be atomic and fail together, then you should use a transaction.

using (new TransactionScope(TransactionScopeOption.Required)) 
{
    connection.Execute(...);
    connection.Execute(...);
}

Or if you want to use BeginTransaction and pass it in, you can also do:

using (var transaction = connection.BeginTransaction()) 
{
    connection.Execute(sql1, params1, transaction);
    connection.Execute(sql2, params2, transaction);
}
like image 97
Kirk Woll Avatar answered Jan 04 '23 22:01

Kirk Woll