简体   繁体   中英

Question About TransactionScope in .NET

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.

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

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