Dion
Dion

Reputation: 954

Using TransactionScope() with NHibernate's BeginTransaction() problem

I'm using NHibernate 3.1.0 with the MySql Connector 6.3.5. As a general rule my repository methods are wrapped in an NHibernate transaction. However the service or application code calling the repository methods might also require a transaction scope - therefore the mixing of NHibernate transactions with .NET's TransactionScope. A simulated test looks like this:

[Test]
public void CanPerformNestedSave()
{
    using (var tx = new TransactionScope())
    {
        var user = new AdminUser { Email = "[email protected]", Name = "Test User 1", Password = "123" };

        using (ISession session = OpenSession())
        {
            using (var tx = session.BeginTransaction())
            {
                entity.ModifiedAt = DateTime.Now;
                session.SaveOrUpdate(entity);
                tx.Commit();

                return entity;
            }
        }

        tx.Complete();
    }
}

The test fails with the following error:

NHibernate.TransactionException : Begin failed with SQL exception ----> System.InvalidOperationException : Nested transactions are not supported.

I've scoured the web to find a solution to this scenario and hopefully the community on StackOverflow can help.

Upvotes: 1

Views: 2017

Answers (1)

Iulian Margarintescu
Iulian Margarintescu

Reputation: 2666

I've blogged about this here.

In the blog post NServiceBus creates the outer TransactionScope for the handlers and the Nhibernate session and transactions are used inside the handler.

Upvotes: 1

Related Questions