Thursday, January 2, 2014

C# - Transactions

There are 2 main types of transaction; Connection transactions and Ambient transactions. Connection transaction is tied to one SqlConnection. Ambient transaction allows multiple SqlConnections.

Connection transaction
using (SqlConnection conn = new SqlConnection(_connStr))
    {
        conn.Open();
        SqlTransaction trans = conn.BeginTransaction();
        try{
            using (SqlCommand cmd = new SqlCommand(, conn, trans))
            {
                //sql work here
                trans.Commit(); 
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            try
            {
                trans.Rollback();
            }
            catch (Exception exRollback)
            {
                // Throws an InvalidOperationException if the connection is closed or the transaction has already been rolled back on the server.
                Console.WriteLine(exRollback.Message);
            }
        }
}
Ambient transaction
    try
    {
        using (TransactionScope scope = new TransactionScope())
        {
            //some methods here
            scope.Complete();
        }
    }
    catch (TransactionAbortedException ex)
    {
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
    }


  • http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.100).aspx

No comments:

Post a Comment