Reputation: 3435
I am trying to backup and restore sql server 2008r2 database, and i successfully backup my database , But the problem is when i am trying to restore my DB its showing the following error Restore failed for Server 'XXXX-PC\SQLEXPRESS'
And Another important thing is that , When i Close the DB Connection (From server Explorer [right-click->Close Connection]) its working Normally And Correctly
Below is my Backup And Restore Code Please help me to fix the problem
public static void BackupDatabase(string backUpFile)
{
ServerConnection con = new ServerConnection(@"XXXX-PC\SQLEXPRESS");
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = "testBD";
BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
source.Devices.Add(destination);
//source.Devices.AddDevice(@"G:\MyBackUp.bak", DeviceType.File);
source.SqlBackup(server);
con.Disconnect();
}
public static void RestoreDatabase(string backUpFile)
{
ServerConnection con = new ServerConnection(@"XXXX-PC\SQLEXPRESS");
Server server = new Server(con);
Restore destination = new Restore();
destination.Action = RestoreActionType.Database;
destination.Database = "testBD";
BackupDeviceItem source = new BackupDeviceItem(backUpFile, DeviceType.File);
destination.Devices.Add(source);
destination.ReplaceDatabase = true;
con.Disconnect();
server.ConnectionContext.Disconnect();
destination.SqlRestore(server);
}
This is the error :
This is the error message in detail:
Upvotes: 0
Views: 436
Reputation: 32667
My guess is that your restore process can't get exclusive access to the database. The Server SMO object has a KillAllProcesses method that takes a database as an argument and does what it says on the tin.
Upvotes: 2