Refactoring ADO.NET - SqlTransaction vs. TransactionScope

前端 未结 6 653
悲哀的现实
悲哀的现实 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:42

    Microsoft recommends using transaction scope:

    http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx

    The basic idea is that transaction scope will manage the "ambient transaction context" for you. You start by talking to one database, you have an sql transaction, then you talk to database number 2, and the transaction is elevated to a distributed transaction.

    Transaction scope does work for you, so that you can concentrate on the functionality of the system, rather than the plumbing.

    EDIT

    When you use a transaction scope everything within that scope is covered by the transaction. You therefore, save a line of code, where you connect the command to the transaction. This is a possible source of error, for example if there were one chance in 1000 that this line had been forgoten, how many would you be missing.

    EDIT 2

    Agree with comment on Triynko below. However, we use Entity Framework, EF will automatically close and reopen a connection in order to enlist it in a transaction. It does not physically close the connection more like, it releases it to the connection pool and gets a new one, which can be the same one or can be a different one.

提交回复
热议问题