Difference between transaction scope and manually defined transactions?

Hi, just by reading about using transaction scrope, I used to do transactions inside the same DB class, for example

try
            {
                con.Open();
                tran = con.BeginTransaction();
                OleDbCommand myCommand1 = new OleDbCommand(query1, con);
                OleDbCommand myCommand2 = new OleDbCommand(query2, con);
                myCommand .Transaction = tran;
                // Save Master
                myCommand1.ExecuteNonQuery();

                // Save Childred
                myCommand2.ExecuteNonQuery();

                // Commit transaction 
                tran.Commit();

            }
catch (OleDbException ex)
                {
                    tran.Rollback();
                    lblError.Text = "An error occured " + ex.ToString();
                }

                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }

                }

But now I find out that I can execute a transaction inside the Business Logic level, simply using the transaction scope object and using separate DB classes, such as

   public static int Save(Employee myEmployee)
    {
      using (TransactionScope myTransactionScope = new TransactionScope())
      {
        int RecordId = EmpDB.Save(myEmployee);

        foreach (Address myAddress in myEmployee.Addresses)
        {
          myAddress.EmployeeId = EmployeeId;
          AddressDB.Save(myAddress);
        }

        foreach (PhoneNumber myPhoneNumber in myEmployee.PhoneNumbers)
        {
          myPhoneNumber.EmployeeId = EmployeeId;
          PhoneNumberDB.Save(myPhoneNumber);
        }

        myTransactionScope.Complete();

        return EmployeeId;
      }
    }

Which of the recommended coding techniques and why? Is it safe to use a transaction? Is this the last way to do something? I am confused in both methods.

Thanks in advance.

+3
source share
1 answer

, try/catch. "" , , , .

, , . , ( ) .

using (TransactionScope myTransactionScope = new TransactionScope())
+1

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


All Articles