Daniel Allen Langdon Daniel Allen Langdon - 8 months ago 32
SQL Question

What is the best way to rollback a .net transaction?

This question is related to my question: http://stackoverflow.com/questions/3072986/sql-server-and-transactionscope-with-msdtc-sporadically-cant-get-connection

I'm doing some transaction programming using the .net

class. If I understand correctly, I can do some SQL operations within a transaction by wrapping the SQL calls inside a
using ts as new TransactionScope()
block, or by using
new TransactionScope()
and then
at the end.

To commit the transaction, MSDN says to use
. Supposing that I want to rollback the transaction under certain circumstances, is it sufficient to simply call
without calling the Commit method first? Is that good practice, or is this supposed to be done some other way?


if you know you want to rollback then do that explicitly. You are not guaranteed that Dispose will rollback (in the case where complete has been called, the transaction will be committed when you call Dispose)

to your question about using or new/Dispose they are not equivalent

using(var ts = new TransactionScope())

is equivalent to

TransactionScope ts;
  ts = new TransactionScope();

to answer your follow up question no if you call Dispose you will not have your transaction "hanging around" it will either commit or rollback. However if you use the new/dispose as you wrote it (no finally block) you can have a situation where dispose isn't called when you expect it to be (in the case of an exception)