7

我有一种情况(我猜这很标准),我需要执行一些业务计算并在数据库中创建一堆记录。如果在任何时候出现任何问题,我需要从数据库中回滚所有内容。显然我需要某种交易。我的问题是我在哪里实现事务支持。这是我的例子

//BillingServices - This is my billing service layer. called from the UI
public Result GenerateBill(BillData obj)
{
     //Validate BillData

     //Create a receivable line item in the receivables ledger 
     BillingRepository.Save(receivableItem);

     //Update account record to reflect new billing information
     BillingRepository.Save(accountRecord);

     //...do a some other stuff
     BillingRepository.Save(moreStuffInTheDatabase);
}

如果对数据库的任何更新失败,我需要将其他更新回滚并退出。我是否只是通过我可以调用的存储库公开一个 Connection 对象

Connection.BeginTransaction()

还是我只是在服务层中进行验证,然后在存储库中调用一种方法来保存所有对象并处理事务?这对我来说似乎不太正确。似乎它会迫使我在数据层中投入大量的业务逻辑。

什么是正确的方法?如果我需要跨越存储库(或者那将是糟糕的设计)怎么办?

4

1 回答 1

5

我假设您在这里使用.NET。在这种情况下,您可以简单地将整个代码部分包装在带有实例的using语句TransactionScope中,它将为您处理事务语义。您只需在最后调用该Complete方法

//BillingServices - This is my billing service layer. called from the UI
public Result GenerateBill(BillData obj)
{
     // Create the transaction scope, this defaults to Required.
     using (TransactionScope txScope = new TransactionScope())
     {
          //Validate BillData

          //Create a receivable line item in the receivables ledger 
          BillingRepository.Save(receivableItem);

          //Update account record to reflect new billing information
          BillingRepository.Save(accountRecord);

          //...do a some other stuff
          BillingRepository.Save(moreStuffInTheDatabase);

          // Commit the transaction.
          txScope.Complete();
     }
}

如果发生异常,这具有Complete退出代码块时不调用的效果;退出语句 范围时调用接口实现上的方法DisposeTransactionScopeIDisposableusing

Dispose调用中,它检查事务是否完成(Complete成功时设置此状态)。如果未设置该状态,它将执行回滚。

然后,您可以将其嵌套在其他TransactionScope实例中(在同一线程上的调用堆栈中更深),以跨多个存储库创建更大的事务。

于 2009-03-24T19:47:39.183 回答