如何在 NHibernate 中进行嵌套事务? [英] How do I do nested transactions in NHibernate?

查看:30
本文介绍了如何在 NHibernate 中进行嵌套事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 NHibernate 中进行嵌套事务,我该如何实现它们?我使用的是 SQL Server 2008,所以 DBMS 肯定支持.

Can I do nested transactions in NHibernate, and how do I implement them? I'm using SQL Server 2008, so support is definitely in the DBMS.

我发现如果我尝试这样的事情:

I find that if I try something like this:

using (var outerTX = UnitOfWork.Current.BeginTransaction())
{
    using (var nestedTX = UnitOfWork.Current.BeginTransaction())
    {
        ... do stuff
        nestedTX.Commit();
    }

    outerTX.Commit();
}

然后到 outerTX.Commit() 时,事务已变为非活动状态,并导致会话 AdoTransaction 上出现 ObjectDisposedException.

then by the time it comes to outerTX.Commit() the transaction has become inactive, and results in a ObjectDisposedException on the session AdoTransaction.

因此,我们是否应该创建嵌套的 NHibernate 会话?还是我们应该使用其他一些类来包装事务(我听说过 TransactionScope,但我不确定那是什么)?

Are we therefore supposed to create nested NHibernate sessions instead? Or is there some other class we should use to wrap around the transactions (I've heard of TransactionScope, but I'm not sure what that is)?

我现在使用 Ayende 的 UnitOfWork 实现(感谢 Sneal).

I'm now using Ayende's UnitOfWork implementation (thanks Sneal).

请原谅我在这个问题上的任何幼稚,我还是 NHibernate 的新手.

Forgive any naivety in this question, I'm still new to NHibernate.

谢谢!

编辑:我发现您可以使用 TransactionScope,例如:

EDIT: I've discovered that you can use TransactionScope, such as:

using (var transactionScope = new TransactionScope())
{
    using (var tx = UnitOfWork.Current.BeginTransaction())
    {
        ... do stuff
        tx.Commit();
    }

    using (var tx = UnitOfWork.Current.BeginTransaction())
    {
        ... do stuff
        tx.Commit();
    }

    transactionScope.Commit();
}

但是我对此并不那么兴奋,因为它使我们只能使用 SQL Server,而且我发现如果数据库是远程的,那么您必须担心启用 MSDTC...组件出错.嵌套事务在 SQL 中非常有用且易于执行,以至于我假设 NHibernate 会以某种方式模拟相同的...

However I'm not all that excited about this, as it locks us in to using SQL Server, and also I've found that if the database is remote then you have to worry about having MSDTC enabled... one more component to go wrong. Nested transactions are so useful and easy to do in SQL that I kind of assumed NHibernate would have some way of emulating the same...

推荐答案

NHibernate 会话不支持嵌套事务.

NHibernate sessions don't support nested transactions.

以下测试在 2.1.2 版本中始终为真:

The following test is always true in version 2.1.2:

var session = sessionFactory.Open();
var tx1 = session.BeginTransaction();
var tx2  = session.BeginTransaction();
Assert.AreEqual(tx1, tx2);

您需要将其包装在 TransactionScope 中以支持嵌套事务.

You need to wrap it in a TransactionScope to support nested transactions.

必须启用 MSDTC 否则会报错:

MSDTC must be enabled or you will get error:

{"分布式事务管理器 (MSDTC) 的网络访问已被禁用.请使用组件服务管理工具在 MSDTC 的安全配置中为网络访问启用 DTC."}

这篇关于如何在 NHibernate 中进行嵌套事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆