Many examples out there advocate explicit rollback of database transactions, along the lines of:
using (var transaction = ...)
{
try
{
// do some reading and/or writing here
transaction.Commit();
}
catch (SqlException ex)
{
// explicit rollback
transaction.Rollback();
}
}
However, I tend to do this:
using (var transaction = ...)
{
// do some reading and/or writing here
transaction.Commit();
}
When an exception occurs, I’m just relying on the implicit rolling back of transactions that aren’t committed.
Is there any problem relying on this implicit behavior? Does anyone have a convincing reason why I shouldn’t be doing it this way?
No, its not specifically needed, however I can think of 2 reasons why it might be a good idea:
Some might argue that using
transaction.Rollback()makes it clearer under what circumstances the transaction will not be committed.When dealing with transactions it is important to realise the certain locks will only be released when the transaction is rolled back or committed. If you are using the
usingstatement then the transaction will be rolled back when the transaction is disposed of, however if for some reason you need to do some error handling inside theusingblock, it may be advantageous to rollback the transaction (removing the locks) before performing complex / time consuming error handling.