I have the following function:
public void RestoreDatabase(String databaseName, String backUpFile, String serverName, String userName, String password)
{
SqlConnection.ClearAllPools();
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Restore rstDatabase = new Restore();
rstDatabase.Action = RestoreActionType.Database;
rstDatabase.Database = databaseName;
BackupDeviceItem bkpDevice = new BackupDeviceItem(backUpFile, DeviceType.File);
rstDatabase.Devices.Add(bkpDevice);
rstDatabase.ReplaceDatabase = true;
rstDatabase.SqlRestore(sqlServer);
}
I was trying to set the DB to single user mode first, before restoring the backup. I tried this code:
private string singleUserCmd = "alter database db-name set SINGLE_USER";
private string multiUserCmd = "alter database db-name set MULTI_USER";
private void SetSingleUser(bool singleUser, SqlConnectionStringBuilder csb)
{
string v;
if (singleUser)
{
v = singleUserCmd.Replace("db-name", csb.InitialCatalog);
}
else
{
v = multiUserCmd.Replace("db-name", csb.InitialCatalog);
}
SqlCommand cmd = new SqlCommand(v, new SqlConnection(csb.ToString()));
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
finally
{
cmd.Connection.Close();
}
}
The problem seems to be that single user mode is for that connection, preventing anyone else from doing anything. I need it to be for the connection that restores the backup.