title: How does TransactionScope roll back transactions?
body: <p>I'm writing an integration test where I will be inserting a number of objects into a database and then checking to make sure whether my method retrieves those objects.</p>
  
  <p>My connection to the database is through NHibernate...and my usual method of creating such a test would be to do the following:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>However, I've recently found out about <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx" rel="noreferrer">TransactionScope</a> which apparently can be used for this very purpose...</p>
  
  <p>Some <a href="http://dotnetslackers.com/articles/ado_net/Managing_Transactions_using_TransactionScope.aspx" rel="noreferrer">example code I've found</a> is as follows:</p>
  
  <pre><code>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;
  
  }
  </code></pre>
  
  <p>I believe that if I don't include the line <code>txScope.Complete()</code> that the data inserted will be rolled back. But unfortunately I don't understand how that is possible... how does the <code>txScope</code> object keep a track of the <code>deptAdapter</code> and <code>empAdapter</code> objects and their transactions on the database.</p>
  
  <p>I feel like I'm missing a bit of information here...am I really able to replace my <code>BeginTransaction()</code> and <code>RollbackTransaction(</code>) calls by surrounding my code using <code>TransactionScope</code>?</p>
  
  <p>If not, how then does <code>TransactionScope</code> work to roll back transactions?</p>