When using TransactionScope it apperars that if internally executed code rolled back the transaction than the parent transaction will rollback as well. Which is good for me. But when disposing that scope it throws an exception meaning that transaction was rolled back already and aborted.
So what is the right way to handle that and properly dispose the scope?
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using (var conn = GetConnection())
{
string query =
@"some query that may contain transaction itself
or some SP whith transaction included"
using (var command = new SqlCommand(query, conn))
command.ExecuteNonQuery();
}
}
scope.Complete();
} // Exception here
Best Answer
scope.Dispose()
may throwTransactionAborted
exception even ifscope.Complete()
has been called. For example some stored procedures a smart enough to handle exceptions and abort transaction inside T-SQL script usingT-SQL TRY/CATCH
constructw/o
throwing exception to the caller. So I would consider the safest approach I would suggest is as follows:And don't worry about disposing
TransactionScope
. scope.Dispose performs whatever necessary to clean it up before throwingTransactionAborted
exception.