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();
}
- Is the above approach any good? Is it wise to use a static class for the respository or will that create problems?
- Is there a way to do this without having to pass a command (cmd) object around?
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:
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
ObjectContextclass in LINQ-to-Entities and theDataContextclass in LINQ-to-SQL are both examples of units of work (you perform operations and then save them in a batch).