chobo
chobo

Reputation: 32281

How to manage ado.net transaction

I'm not sure what a good way to manage this transaction in code would be.

Say I have the following

Service layer (non-static class) Repository layer (static class)

// Service layer class

/// <summary>
/// Accept offer to stay
/// </summary>
public bool TxnTest()
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        SqlTransaction txn = conn.BeginTransaction();

        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = txn;

            try
            {
                DoThis(cmd);
                DoThat(cmd);

                txn.Commit();
            }
            catch (SqlException sqlError)
            {
                txn.Rollback();
            }
        }
    }
}

// Repo Class

   /// <summary>
    /// Update Rebill Date
    /// </summary>
    public static void DoThis(SqlCommand cmd)
    {
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@SomeParam", 1);

        cmd.CommandText = "Select * from sometable1";
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
    }



 /// <summary>
        /// Update Rebill Date
        /// </summary>
        public static void DoThat(SqlCommand cmd)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@SomeParam", 2);

            cmd.CommandText = "Select * from sometable2";
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
  1. Is the above approach any good? Is it wise to use a static class for the respository or will that create problems?
  2. Is there a way to do this without having to pass a command (cmd) object around?

Upvotes: 1

Views: 2232

Answers (1)

casperOne
casperOne

Reputation: 74530

You might want to take a look at the unit of work pattern.

The unit of work pattern defines exactly what it suggests, a unit of work that is committed all at once, or not at all.

This occurs by defining an interface that has two parts:

  • Methods that handle your insert, update, deleted operations (note, you don't have to expose all of these operations, and you aren't limited to one entity type)
  • A method to commit (if you rollback, you simply don't call commit). This is where you would handle the transaction as well as the inserting, updating and/or deletion of all the entities that registered to be changed.

Then, you would pass an implementation of this interface around, and commit the changes at the outer boundaries (your service) when all the operations are complete.

Note that the ObjectContext class in LINQ-to-Entities and the DataContext class in LINQ-to-SQL are both examples of units of work (you perform operations and then save them in a batch).

Upvotes: 3

Related Questions