gpt4 book ai didi

unit-testing - 带有 SQLite 内存数据库和 NHibernate 的 TransactionScope

转载 作者:行者123 更新时间:2023-12-03 17:18:00 25 4
gpt4 key购买 nike

我遇到了使用 TransactionScope 时事务不回滚的问题.

我们将 NHibernate 与内存中的 SQLite 数据库一起使用,因此在应用程序的整个生命周期(在这种情况下,是一些单元测试)期间,我们只能使用一个 db 连接。

using (var ts = new TransactionScope(TransactionScopeOption.Required, 
TimeSpan.Zero))
{
using (var transaction = _repository.BeginTransaction())
{
_repository.Save(entity);
transaction.Commit();
}
// ts.Complete(); <- commented Complete call still commits transaction
}

即使我删除了 NHibernate 的内部嵌套事务,代码如下所示,事务仍然提交。
using (var ts = new TransactionScope(TransactionScopeOption.Required, 
TimeSpan.Zero))
{
_repository.Save(entity);
} // no Complete(), but the transaction still commits

是否期待在 TransactionScope 内有一个新打开的 SQLite 连接?阻止以便在交易中登记它?

同样,我无法为它提供新连接,因为这会清除数据库。

使用 NHibernate 3.0 和 SQLite 1.0.66.0,在撰写本文时均为最新版本。

注:使用 transaction.Rollback()关于 NHibernate ITransaction对象正确回滚事务,它只是 TransactionScope似乎不起作用的支持。

最佳答案

我想我可能已经找到了原因。如果连接不是从 TransactionScope 块内部打开的,它将不会被登记在事务中。

这里有一些信息:
http://msdn.microsoft.com/en-us/library/aa720033(v=vs.71).aspx

解决方案:

我已经有了 .BeginTransaction()方法在我的存储库中,所以我想我会在那里的环境事务中手动登记连接。

这是我最终得到的代码:

    /// <summary>
/// Begins an explicit transaction.
/// </summary>
/// <returns></returns>
public ITransaction BeginTransaction()
{
if (System.Transactions.Transaction.Current != null)
{
((DbConnection) Session.Connection).EnlistTransaction(System.Transactions.Transaction.Current);
}
return Session.BeginTransaction();
}

这是我如何使用它:
  using (var ts = new TransactionScope(TransactionScopeOption.Required, TimeSpan.Zero))
using (var transaction = repository.BeginTransaction())
{
repository.Save(entity);
transaction.Commit(); // nhibernate transaction is commited
// ts.Complete(); // TransactionScope is not commited
} // transaction is correctly rolled back now

关于unit-testing - 带有 SQLite 内存数据库和 NHibernate 的 TransactionScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5369465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com