title: EF4 Code First, TDD, CRUD, and Transactions
body: <p>In the past, I've written unit tests for simple CRUD operations when creating data access/repository code that look something like this:</p>
  
  <pre><code>using(var connection = new WhateverConnection(connectionString))
  {
      connection.Open();
      using(var transaction = connection.BeginTransaction())
      {
          try
          {
              //test the CRUD operation
          }
          finally
          {
              //gets rid of any stuff created during the test
              transaction.Rollback();
          }
      }
  }
  </code></pre>
  
  <p>I was messing around with EF4 Code First today, and I realized that I have no idea how this testing scenario translates in the Entity Framework lexicon.  It seems that, if I call <code>DbContext.SaveChanges()</code>, it saves <strong>and</strong> commits, regardless of whether or not <code>AcceptAllChanges()</code> was called.  Even using <code>ObjectContext</code> instead of <code>DbContext</code>, I can't figure out how this simple test scenario can be recreated without manually cleaning up any mock/test objects created.  I did read <a href="http://msdn.microsoft.com/en-us/library/bb738523.aspx" rel="nofollow">this article on MSDN</a>, but <code>TransactionScope</code> doesn't really have a <code>Rollback</code> type method either.  Do I use <code>TransactionScope</code> and never call <code>Complete</code>?  Is there another method or manner of using DbContext and/or ObjectContext in order to Rollback during unit tests?  Do I need to completely re-adjust my thinking for TDD with EF4 Code First?</p>