SteveM
SteveM

Reputation: 305

Nhibernate session.BeginTransaction() vs. transaction.Begin()

My question is related to use of nhibernate transactions

Is the transaction.Begin() below a problem? or just redundant?

using (var transaction = session.BeginTransaction())
{
    transaction.Begin();
    action();
    transaction.Commit();
}

Upvotes: 6

Views: 11238

Answers (2)

Freelancer
Freelancer

Reputation: 9064

beginTransaction as it states begins a transaction,

on the other hand

session.Transaction will return the current active transaction if null will create one.

The NHibernate session tracks the current active (not committed or rolled back) transaction.

If you call ISession.Transaction when no transaction has yet been created yet during the life time of the session, the session will create a new transaction object at that point in time, but won't begin it yet. When you call ISession.BeginTransaction, the session will see if their is already a transaction object that has been created before, but not yet completed. If so, it will return this transaction object. If not, it will create a new transaction object, begin it and store a reference to this new object.

On transaction completion, the transaction object notifies the session to which it belongs that it has completed, on which the session will release its reference to the transaction object. Any following call to ISession.Transaction or ISession.BeginTransaction will then cause the creation of a new transaction object.

NHibernate does not support reuse of transaction objects for more than one transaction (this behaviour may be different from Hibernate, which does seem to support reuse of transaction objects).

Refer this document.

Upvotes: 3

SteveM
SteveM

Reputation: 305

After checking the source, transaction.Begin() is in fact redundant - a harmless no-op.

link to source

Upvotes: 8

Related Questions