Search code examples
architecturedata-access-layerdapper

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?


Solution

  • 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();
         }
    }