批次處理 (新增/更新/刪除多筆) 需原子性:要么全成功、要么全失敗。本文擴充 DAL 支援資料庫交易,為後續批次介面奠基。
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlTransaction tx = conn.BeginTransaction();
try
{
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = tx;
cmd.CommandText = "UPDATE ...";
cmd.ExecuteNonQuery();
// 更多命令...
tx.Commit();
}
catch
{
tx.Rollback();
throw;
}
finally { conn.Close(); }
using (TransactionScope scope = new TransactionScope())
{
// 多個 DAL/BLL 操作,甚至跨資料庫
ProductsBLL.UpdateProduct(...);
OrdersBLL.CreateOrder(...);
scope.Complete(); // 無例外則 Commit
}
// 例外拋出或未呼叫 Complete → 自動 Rollback
SqlTransaction:public partial class ProductsTableAdapter
{
public void BeginTransaction()
{
this.Connection.Open();
this.Transaction = this.Connection.BeginTransaction();
foreach (SqlCommand cmd in this.CommandCollection)
cmd.Transaction = this.Transaction;
}
public void CommitTransaction()
{
this.Transaction.Commit();
this.Connection.Close();
}
public void RollbackTransaction()
{
this.Transaction.Rollback();
this.Connection.Close();
}
}
public void DeleteProductsWithTransaction(List<int> productIDs)
{
ProductsTableAdapter adapter = new ProductsTableAdapter();
adapter.BeginTransaction();
try
{
foreach (int id in productIDs)
adapter.Delete(id);
adapter.CommitTransaction();
}
catch
{
adapter.RollbackTransaction();
throw;
}
}
DAL 層支援交易是批次處理架構基石。TransactionScope 為現代首選,SqlTransaction 適用於需精細控制單一連接的舊代碼遷移。後續章節將建構批次新增/更新/刪除完整介面。