2011-01-05 1 views
1

J'ai trouvé un point de départ ci-dessous, mais je crains de pouvoir manquer des appels à CreateDbBackup() et RestoreDbBackup(). J'espérais pouvoir écrire et utiliser un attribut sur mes tests. Est-ce possible? Comment? J'utilise la bibliothèque MSTest et C# 4.0.Je cherche un code qui me permettra de sauvegarder la base de données SQL Server 2005/2008/2008R2 dans les tests C# (MSTest)

http://www.linglom.com/2008/01/12/how-to-backup-and-restore-database-on-microsoft-sql-server-2005/

internal void CreateDbBackup() 
{ 
     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString)) 
     { 
      SqlCommand cmd = con.CreateCommand(); 
      cmd.CommandText = string.Format(@"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath); 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
     } 
    } 

    internal void RestoreDbFromBackup() 
    { 
     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString)) 
     { 
      SqlCommand cmd = con.CreateCommand(); 

      con.Open(); 

      // Make sure to get exclusive access to DB to avoid any errors 
      cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE"; 
      cmd.ExecuteNonQuery(); 

      cmd.CommandText = string.Format(@"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath); 
      cmd.ExecuteNonQuery(); 
     } 
} 

Répondre

2

Jetez un oeil à SQL Server Management Objects (SMO). Vous devriez pouvoir l'utiliser pour sauvegarder et restaurer les bases de données SQL Server.

+0

Merci! Comment officiel/vieux/bien testé est-ce? –

+0

Microsoft a développé cela en commençant par SQL Server 2005. Il peut être installé lors de l'installation de SQL Server. – Bernard

Questions connexes