Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transactions in "dapper-dot-net"

How do I create a transaction if my DAL is using dapper-dot-net?

My c# winform application will be used in network and the data will be saved to a central sql server.

My use case requires use of transactions. Can I do this using dapper, or will I need to use something like NHibernate?

Also, is there any risk or limitation with this framework if I am using stored procedures? Will I need to change my approach due any possible limitations?

like image 426
TechS Avatar asked Dec 31 '12 11:12

TechS


2 Answers

I haven't run into any limitations with using sprocs and the risks you have with dapper are the same risks you would have with sprocs

Here is a simple example on how to use transactions with dapper

using (var connection = Db.GetConnection())
{
     connection.Open();
     IDbTransaction transaction = connection.BeginTransaction();
     try
     {
         var newId= connection.Query<int>(@"Select id from table1 where id=@id", new{id}, transaction).Single();
         connection.Execute(@"INSERT into table1 ...",new {p1, p2}, transaction);
         connection.Execute(@"INSERT into table2 ...",new {p1, p2}, transaction);
         transaction.Commit();
     }
     catch (Exception ex)
     {
         transaction.Rollback();
     }
}
like image 159
mosesfetters Avatar answered Sep 22 '22 07:09

mosesfetters


dapper can use both ado.net transactions and implicit transactions. For ado.net transactions, just create the transaction normally and provide it via the transaction parameter that is available on the main methods. For implicit transactions, just use TransactionScope normally.

like image 36
Marc Gravell Avatar answered Sep 21 '22 07:09

Marc Gravell