title: Delete and recreate database using EntityFramework
body: <p>We are using EF 6 and for some integration tests we want to completely remove our Database, and recreate it using the database context.</p>
  
  <p>We try to get exclusive use of the database, but are getting a database in use errror. This is what we tried:</p>
  
  <pre><code>    private void CreateDatabase()
      {
          MyDbContext context = new MyDbContext();
          SqlConnection sqlConnection = context.Database.Connection as SqlConnection;
  
          LockDb(sqlConnection);
          context.Database.Delete();
          context.Database.CreateIfNotExists();
          UnLockDb(sqlConnection);
          _context = context;
      }
  
      private void LockDb(SqlConnection connection)
      {
          const string cmdText = 
              "USE[master];"
              + "IF exists(select * from sys.databases where name = 'MyDb')"
              + "BEGIN"
              + "  ALTER DATABASE[MyDb] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"
              + "END;";
  
          OpenConnection(connection);
          ExecuteCommand(connection, cmdText);
      }
  </code></pre>
  
  <p>What are we missing?</p>