topher-b
8/14/2015 - 5:00 PM

Transactions

Transactions

using(TransactionScope transaction = new TransactionScope()) {
    CallAMethodThatDoesSomeWork();
    CallAMethodThatDoesSomeMoreWork();
    transaction.Complete();
}
using (SqlTransaction transaction = connection.BeginTransaction()) {
    try {
        // your code
        transaction.Commit();
    }  catch {
        transaction.Rollback();
        throw;
    }
}
using (SqlConnection connection = new SqlConnection("Connection String"))
{
  using (SqlTransaction transaction = connection.BeginTransaction())
  {
    try
    {
      connection.Open();
      using (SqlCommand command = new SqlCommand("SprocName", connection))
      {
        command.CommandType = CommandType.StoredProcedure;
        #region Parameters
        command.Parameters.AddWithValue("@variable", value);
        #endregion
        //Execute as NonQuery
        command.ExecuteNonQuery();
        // OR as Query
        using (SqlDataReader reader = command.ExecuteReader())
        {
          while (reader.Read())
          {
          }
        }
      }
      connection.Close();
      transaction.Commit();
    }
    catch
    {
      transaction.Rollback();
      throw;
    }
  }
}