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 TransactionScope code above structured? This is my first time using it, so I'm trying to make everything as simple as possible.

+3
source share
1 answer

The locks are alright

but what you do is not working well. You basically roll back if not every table has updated rows. You will never know if your transaction has completed or completed. Which could fix the error.

I would rather throw an exception if something went wrong. It would also lead to a rollback. 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();
}
+8
source

Source: https://habr.com/ru/post/1747754/


All Articles