Reputation: 32281
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();
}
Upvotes: 1
Views: 2232
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:
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