【发布时间】:2010-10-04 10:03:33
【问题描述】:
我正在编写一个集成测试,我将在其中将一些对象插入到数据库中,然后检查以确保我的方法是否检索到这些对象。
我与数据库的连接是通过 NHibernate...我通常创建此类测试的方法是执行以下操作:
NHibernateSession.BeginTransaction();
//use nhibernate to insert objects into database
//retrieve objects via my method
//verify actual objects returned are the same as those inserted
NHibernateSession.RollbackTransaction();
但是,我最近发现 TransactionScope 显然可以用于此目的...
public static int AddDepartmentWithEmployees(Department dept)
{
int res = 0;
DepartmentAdapter deptAdapter = new DepartmentAdapter();
EmployeeAdapter empAdapter = new EmployeeAdapter();
using (TransactionScope txScope = new TransactionScope())
{
res += deptAdapter.Insert(dept.DepartmentName);
//Custom method made to return Department ID
//after inserting the department "Identity Column"
dept.DepartmentID = deptAdapter.GetInsertReturnValue();
foreach(Employee emp in dept.Employees)
{
emp.EmployeeDeptID = dept.DepartmentID;
res += empAdapter.Insert(emp.EmployeeName, emp.EmployeeDeptID);
}
txScope.Complete();
}
return res;
}
我相信如果我不包含txScope.Complete() 行,插入的数据将被回滚。但不幸的是,我不明白这怎么可能……txScope 对象如何跟踪deptAdapter 和empAdapter 对象及其在数据库中的事务。
我觉得我在这里遗漏了一些信息......我真的能够通过使用TransactionScope 包围我的代码来替换我的BeginTransaction() 和RollbackTransaction() 调用吗?
如果不是,那么TransactionScope 如何回滚事务?
【问题讨论】:
-
我从未使用过 NHibernate,但也许 this link 会帮助你。
-
如果您正在寻找一种更好的方法来管理您的 NHibernate 会话以将操作分组到事务中,您可能想查看我关于该主题的博客文章 dotnetchris.wordpress.com/2009/01/27/…
标签: c# .net nhibernate transactions transactionscope