いくつかのオブジェクトをデータベースに挿入し、メソッドがそれらのオブジェクトを取得するかどうかを確認する統合テストを書いています。
私のデータベースへの接続は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
ここで少し情報が不足しているように感じます...を使用してコードを囲むことで、 BeginTransaction()
and ) 呼び出しを本当に置き換えることができますか?RollbackTransaction(
TransactionScope
TransactionScope
そうでない場合、トランザクションをロールバックするためにどのように機能しますか?