在没有数据库的情况下使用 SMO 还原数据库正在使用错误

Restore DB using SMO without DATABASE is in use error

我正在使用 SMO 恢复数据库,

 ServerConnection con = new ServerConnection(_serverName, _userName, _password);
 Server server = new Server(con);
 Restore destination = new Restore();
 destination.Action = RestoreActionType.Database;
 destination.Database = _databaseName;
 BackupDeviceItem deviceItem = new BackupDeviceItem(path, DeviceType.File);
 destination.Devices.Add(deviceItem);
 destination.ReplaceDatabase = true;
 destination.NoRecovery = true;
 destination.SqlRestore(server);

我收到异常消息:

无法获得独占访问权限,因为数据库正在使用中。 RESTORE DATABASE 异常终止。

我通过终止连接的进程和数据库解决了这个问题

ServerConnection con = new ServerConnection(_serverName, _userName, _password);
Server server = new Server(con);
Restore destination = new Restore();
destination.Action = RestoreActionType.Database;
destination.Database = _databaseName;
BackupDeviceItem deviceItem = new BackupDeviceItem(path, DeviceType.File);
destination.Devices.Add(deviceItem);
destination.ReplaceDatabase = true;
destination.NoRecovery = true;
server.KillAllProcesses("your db name");
server.KillDatabase("your db name");
destination.SqlRestore(server);