Will a using statement rollback a database transaction if an error occurs?

C#TransactionsRollbackUsing Statement

C# Problem Overview


I've got an IDbTransaction in a using statement but I'm unsure if it will be rolled back if an exception is thrown in a using statement. I know that a using statement will enforce the calling of Dispose()...but does anyone know if the same is true for Rollback()?

Update: Also, do I need to call Commit() explicitly as I have below or will that also be taken care of by the using statement?

My code looks sort of like this:

using Microsoft.Practices.EnterpriseLibrary.Data;

...

using(IDbConnection connection = DatabaseInstance.CreateConnection())
{
    connection.Open();

    using(IDbTransaction transaction = connection.BeginTransaction())
    {
       //Attempt to do stuff in the database
       //potentially throw an exception
       transaction.Commit();
    }
}

C# Solutions


Solution 1 - C#

Dispose method for transaction class performs a rollback while Oracle's class doesn't. So from transaction's perspective it's implementation dependent.

The using statement for the connection object on the other hand would either close the connection to the database or return the connection to the pool after resetting it. In either case, the outstanding transactions should be rolled back. That's why an exception never leaves an active transaction lying around.

Also, yes, you should call Commit() explicitly.

Solution 2 - C#

You have to call commit. The using statement will not commit anything for you.

Solution 3 - C#

I believe that if there's an exception such that Commit() was never called, then the transaction will automatically rollback.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmezoidView Question on Stackoverflow
Solution 1 - C#Sedat KapanogluView Answer on Stackoverflow
Solution 2 - C#jhaleView Answer on Stackoverflow
Solution 3 - C#Tommy HuiView Answer on Stackoverflow