Refactoring ADO.NET - SqlTransaction vs. TransactionScope

前端 未结 6 660
悲哀的现实
悲哀的现实 2020-12-04 23:58

I have \"inherited\" a little C# method that creates an ADO.NET SqlCommand object and loops over a list of items to be saved to the database (SQL Server 2005).

Right

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 00:43

    I prefer TransactionScope. It doesn't work perfectly in every scenario, but in the one you describe, it's the better solution.

    My reasoning:

    1. Enlistment in the Transaction is automatic
    2. Transaction rollback in the event of an Exception is automatic

    Together, the result is a little less code and a generally more robust design, since the system is handling some of the details for me; it's one less thing I have to remember to do.

    In addition, transparent Transaction enrollment can be particularly useful when you have a number of nested methods in your DAL -- although you do have to take care to not accidentally have your transaction turn into a distributed one that requires the DTC, which can happen if you use multiple SqlConnections, even if they point to the same DB.

提交回复
热议问题