Sunday, August 21, 2011

NHibernate non-support for nested transactions, and how to tackle it

We cannot do nested transaction in NHibernate, but we can detect if there's an active transaction and adjust our code's transaction accordingly

[TestMethod]
public void Nh_Can_Detect_Transaction_From_Session_Begin_Transaction() 
{
	// Arrange
	NHibernate.ISession sess = NhModelsMapper.GetSession(connectionString);
	Assert.IsNotNull(sess.Transaction);
	Assert.IsFalse(sess.Transaction.IsActive);


	// Act
	var tx = sess.BeginTransaction();
	
	
	// Assert
	Assert.IsTrue(sess.Transaction.IsActive);
	Assert.AreEqual(sess.Transaction.IsActive, tx.IsActive);

	Assert.IsNotNull(tx);
	Assert.IsNotNull(sess.Transaction);
	Assert.AreSame(sess.Transaction, tx);

	tx.Commit();
	Assert.IsFalse(sess.Transaction.IsActive);
	Assert.AreEqual(sess.Transaction.IsActive, tx.IsActive);

}

No comments:

Post a Comment