ASP .Net 2.0事务处理

{
string connectionString = "
";
IDbConnection connection = new SqlConnection(connectionString);
connection.Open();
IDbCommand command = new SqlCommand();
command.Connection = connection;
IDbTransaction transaction;
transaction = connection.BeginTransaction(); //Enlisting database
command.Transaction = transaction;
try
{
/**//* Interact with database here, then commit the transaction
*/
transaction.Commit();
}
catch
{
transaction.Rollback(); //Abort transaction
}
finally
{
connection.Close();
}
}什么是 System.Transactions?
System.Transactions 是 .NET 2.0 框架中新增的事务控件命名空间。它是一种处理分布式事务的新方式,没有 COM+ 注册和 COM+ 目录的开销。请注意,Microsoft 分布式事务协调器用于初始化事务。
运行情况
同步定单处理中的 Order.Insert() 方法使用 System.Transactions 插入一个定单并更新库存。通过添加对 System.Transaction 命名空间的引用,并将定单插入方法和库存减少方法包装在 TransactionScope 内,我们实现了 Order.Insert() 方法,如代码清单 1 所示。
清单 1. 运行中的 System.Transactions
using System;
using System.Transactions;
using PetShop.IBLLStrategy;
namespace PetShop.BLL {
/// <summary>
/// This is a synchronous implementation of IOrderStrategy
/// By implementing IOrderStrategy interface, the developer can
/// add a new order insert strategy without re-compiling the whole
/// BLL.
/// </summary>
public class OrderSynchronous : IOrderStrategy {
...
/// <summary>
/// Inserts the order and updates the inventory stock within
/// a transaction.
/// </summary>
/// <param name="order">All information about the order</param>
public void Insert(PetShop.Model.OrderInfo order) {
using (TransactionScope ts = new
TransactionScope(TransactionScopeOption.Required)) {
dal.Insert(order);
// Update the inventory to reflect the current inventory
// after the order submission.
Inventory inventory = new Inventory();
inventory.TakeStock(order.LineItems);
// Calling Complete commits the transaction.
// Excluding this call by the end of TransactionScope's
// scope will rollback the transaction.
ts.Complete();
}
}
}
}

