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 method开发者_JS百科s 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 = "user@test.com", 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.
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.
精彩评论