我不确定在代码中管理此事务的好方法是什么。
说我有以下
服务层(非静态类) 存储层(静态类)
// 服务层类
/// <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();
}
}
}
}
// 回购类
/// <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();
}
- 上述方法有什么好处吗?为存储库使用静态类是明智的还是会产生问题?
- 有没有办法做到这一点而不必传递命令(cmd)对象?