Wonderful. IDbConnection and IDbTransaction
How do I use IDbConnection and IDbTransaction with Dapper?
At the moment I am only using IDbConnection
. Something like this:
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
?
+3
source to share
1 answer
Yes, if you need two separate commands that are 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, you can also do:
using (var transaction = connection.BeginTransaction())
{
connection.Execute(sql1, params1, transaction);
connection.Execute(sql2, params2, transaction);
}
+12
source to share