title: Entity Framework C# Code First Migration Unit Testing
body: <hr>
  
  <p>I would like to be able to unit test using my code first/migrations entity framework project.</p>
  
  <p>My current method does the following:</p>
  
  <ol>
  <li>Create the DataContext</li>
  <li>Creates the repository</li>
  <li>Creares unit of working using DataContext</li>
  <li>Creates my service layer</li>
  </ol>
  
  <p>After step 1. I would like to be able say to entity framework, using my migrations/migrations folder recreate the database every time it runs.</p>
  
  <p>I current send in my Datacontext a custom string which represents what connection string to use, my code looks like:</p>
  
  <pre><code>    [TestCase]
      public void TestMethod1()
      {
  
          var systemContextTest = new SystemContext("SystemContextTest");
          IRepository&lt;PublicQueries&gt; repos = new Repository&lt;PublicQueries&gt;(systemContextTest);
          var uow = new UnitOfWork(systemContextTest);
          var service = new PublicQueryService(repos);
          service.Find(0);
      }
  </code></pre>
  
  <p>I just want to be able to create the database, using migrations everytime this test is ran!</p>
  
  <p>Thanks</p>
  
  <p>-UPDATE-</p>
  
  <p>I have tried:</p>
  
  <pre><code>Database.SetInitializer&lt;YourContext&gt;(new MigrateDatabaseToLatestVersion&lt;YourContext, YourMigrationConfiguration&gt;());
  </code></pre>
  
  <p>But this results in </p>
  
  <blockquote>
    <p>System.Data.Entity.Core.EntityCommandExecutionException : An error occurred while executing the command definition. See the inner exception for details.
      ----> System.Data.SqlClient.SqlException : Invalid object name</p>
  </blockquote>
  
  <p>Which means its still not creating it.</p>
  
  <p>I just want to using my migration files/code first migrations to create a new fresh database.</p>
  
  <p>-- UPDATE 2 --</p>
  
  <p>When adding <code>Database.SetInitializer(new DropCreateDatabaseAlways&lt;SystemContext&gt;());</code></p>
  
  <p>I get the following error: </p>
  
  <blockquote>
    <p>System.InvalidOperationException : The DropCreateDatabaseAlways initializer did not drop or create the database backing context 'SystemContext' because Migrations are enabled for the context. Use Migrations to manage the database for this context, for example by running the 'Update-Database' command from the Package Manager Console.</p>
  </blockquote>
  
  <p>My SystemContext Constructor i am using for testing looks like:</p>
  
  <pre><code>      public SystemContext(string connectionstringname) :
          base(connectionstringname)
      {
          Database.SetInitializer&lt;SystemContext&gt;(null);
          Configuration.ProxyCreationEnabled = false;
      }
  </code></pre>