Using a construction with sqlTransaction, depending on the number of different action results

I am wondering if the following code will be considered safe?

using (SqlConnection cn = new SqlClient.SqlConnection(connectionString))
{
   cn.Open();
   using (SqlTransaction tr = cn.BeginTransaction())
   {
      try
      {

         if (!Data.DoSomething1(tr, p1, p2))
         {
            tr.Rollback();
            return false;
         }

         foreach (ItemType item in Items)
         {
            if (!Data.DoSomething2(tr, p3, p4))
            {
               tr.Rollback();
               return false;
            }
         }

         tr.Commit();
         return true;
      }
      catch (Exception myErr)
      {
         if (tr != null)
            tr.Rollback();

         throw myErr;
      }
      finally
      {
         if (cn != null)
         {
            cn.Close();
            cn.Dispose();
         }
      }
   }
}

I wanted to pass the transaction 'tr' via the ref link, but could not, because it is in the using construct. I would like to hear suggestions for a better approach in such situations.

Hi

+3
source share
2 answers

You do not need to pass the transaction by reference. This is a reference type, so when you pass it to a function, you already provide a link. What you do is beautiful.

Although there are a few more things in your code that are not directly related to your question:

  • throw; not throw myErr;.
  • , using. using.
+1

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


All Articles