简体   繁体   中英

How to rollback a transaction using 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM