somemvcperson
somemvcperson

Reputation: 1253

Does Nhibernate session.BeginTransaction auto rollback on exception within Using

Ok sorry for the long subject name...

If I do the following:

using (var transaction = session.BeginTransaction())
{
    // do something
    transaction.Commit();
}

If my do something caused an exception, would it auto rollback, or do I need to explicitly check for this like below:

using (var transaction = session.BeginTransaction())
{
    try
    {
        // do something
        transaction.Commit();
    }
    catch (Exception)
    {
        transaction.Rollback();
    }
}

Upvotes: 17

Views: 4223

Answers (1)

Jamie Ide
Jamie Ide

Reputation: 49261

It's a safe assumption that the transaction will be rolled back if the commit fails in a using block.

ITransaction wraps an ADO.NET transaction behind the scenes, so it depends on the provider specific implementation. The Dispose method in the source code I checked (2.1) assumes that calling Dispose on the internal IDbTransaction rolls it back.

Upvotes: 15

Related Questions