title: Intermittent Fails after Database Restore
body: <p>I am restoring a database which is used on a c# based test harness. It is restored on every test run and sometimes after an individual test.</p>
  
  <p>I am having intermittent errors when the database sometimes fails after the restore when I try a new query.</p>
  
  <p>I am first setting it to offline:</p>
  
  <pre><code>using (SqlConnection conn = new SqlConnection(GetConnectionString("MasterDatabase")))
          using (SqlCommand cmd = new SqlCommand(@"ALTER DATABASE MYDB SET OFFLINE WITH ROLLBACK IMMEDIATE", conn))
          {
              conn.Open();
              cmd.CommandType = CommandType.Text;
              cmd.ExecuteNonQuery();
              cmd.Dispose();
          }
  </code></pre>
  
  <p>And then restoring:</p>
  
  <pre><code> using (SqlConnection conn = new SqlConnection(GetConnectionString("MasterDatabase")))
          using (SqlCommand cmd = new SqlCommand(@"Restore Database MYDB
                  FROM Disk = 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\MYDB.bak'
                  WITH REPLACE, MOVE 'MYDB_Dat' TO 'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MYDB.mdf',
                  MOVE 'MYDB_Log' TO 'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MYDB.ldf'", conn))
          {
              conn.Open();
              cmd.CommandType = CommandType.Text;
              cmd.ExecuteNonQuery();
              cmd.Dispose();
          }
  </code></pre>
  
  <p>Any further database calls intermittently fail.</p>