Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rollback a transaction using dapper

Tags:

c#

.net

dapper

I have this:

            using (var con= new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString))
            {
                try
                {
                  // many transactions
                }
                catch (Exception e)
                {
                    con.BeginTransaction().Rollback();
                }
            }

Will this work is my question.. I know another method is to make a transaction then open it then rollback.

like image 548
NoviceDeveloper Avatar asked Mar 23 '16 19:03

NoviceDeveloper


1 Answers

You could use a TransactionScope variable in a using block at the same level of the using block of the SqlConnection

using (TransactionScope scope = new TransactionScope())
using (var con= new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString))
{
    try
    {
       // many transactions
       scope.Complete();
    }
    catch (Exception e)
    {
        // Not needed any rollback, if you don't call Complete
        // a rollback is automatic exiting from the using block
        // con.BeginTransaction().Rollback();
    }
}
like image 110
Steve Avatar answered Sep 23 '22 02:09

Steve