3
using (TransactionScope scope = new TransactionScope())
{
    int updatedRows1 = custPh.Update(cust.CustomerID, tempPh1, 0);
    int updatedRows2 = custPh.Update(cust.CustomerID, tempPh2, 1);
    int updatedRows3 = cust.Update();

    if (updatedRows1 > 0 && updatedRows2 > 0 && updatedRows3 > 0)
    {
        scope.Complete();
    }
}

Is the above TransactionScope code structured correctly? This is my first time using it so i'm trying to make as simple as i can.

Steven
  • 166,672
  • 24
  • 332
  • 435
peace
  • 837
  • 2
  • 12
  • 18
  • 1
    You're using it just fine. You might want to make sure you're joining / not joining an ambient transaction depending on your requirements. You set those with a TransactionOptions parameter. http://simpleverse.wordpress.com/2008/08/05/using-transactionscope-for-handling-transactions/ – Mike Atlas May 30 '10 at 14:01
  • @Mike. You should create an answer, since it is correct. – Steven May 30 '10 at 14:21
  • 1
    Actually I think that article might be out of date Mike. TransactionScope is no longer just a wrapper around DTC, and this makes it much more usable: http://stackoverflow.com/questions/1155941/transactionscope-has-it-gotten-better – Brian MacKay May 30 '10 at 14:41
  • To expand on Mike's comment, the default IsolationLevel for TransactionScope is Serializable (I once assumed it was ReadCommitted and was quite surprised by the database deadlocks that were occurring). The IsolationLevel can be set via the TransactionOptions struct parameter to the TransactionScope constructor. What Mike is referring to is the TransactionScopeOption enumeration parameter. – Dan Terry May 30 '10 at 14:54

1 Answers1

8

Locks fine,

but what you are doing is bad desing. You are basically doing a rollback if not every table has updated rows. You will never know if your transaction completed or failed. Which could make resolving an error a pain.

I would prefer throwing the exception if something went wrong. That would lead to a rollback, too. because scope.Complete() is never reached.

using (TransactionScope scope = new TransactionScope())
{
    int updatedRows1 = custPh.Update(cust.CustomerID, tempPh1, 0);
    int updatedRows2 = custPh.Update(cust.CustomerID, tempPh2, 1);
    int updatedRows3 = cust.Update();

    if (updatedRows1 == 0 || updatedRows2 == 0 || updatedRows3 == 0)
        throw new Exception("Not all rows could be updated");

    scope.Complete();
}
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189