[英]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 // 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();
}
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). 请注意,LINQ-to-Entities中的
ObjectContext
类和LINQ-to-SQL中的DataContext
类都是工作单元的示例(您执行操作然后将它们保存在批处理中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.