views:

856

answers:

1

I have the following code (simplified for the sake of discussion). What I don't understand is why the session.Transaction property returns a different transaction after a rollback.

For instance, this means that the property Session.Transaction.WasRolledBack is of little help unless I store a reference to the first transaction and check that transaction's property.

Can anybody provide some insight here?

int transId = session.Transaction.GetHashCode();

using (var tx = session.BeginTransaction())
{
   Assert.AreEqual(transId, tx.GetHashCode());

   tx.Rollback();

   Assert.AreEqual(transId, tx.GetHashCode());
   Assert.AreEqual(transId, session.Transaction.GetHashCode()); // Fails
}

Update:

David Walschots' answer is very helpful and precise. Also, I found the following in the Nhibernate Documentation: "If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent."

+1  A: 

From NHibernate in Action (Kuaté, Harris, Bauer, King):

"After committing a transaction, the NHibernate session replaces it with a new transaction. This means you should keep a reference to the transaction you're committing if you think you'll need it afterward. This is necessary if you need to call transaction.WasCommited. session.Transaction.WasCommitted always returns false."

Most likely the same applies to the Transaction.WasRolledBack property.

David Walschots