I try to restore the database like this:
SQL = @"RESTORE DATABASE MyDataBase TO DISK='d:\MyDATA.BAK'";
Cmd = new SqlCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
but I always get error:
Msg 3102, Level 16, State 1, Line 7
RESTORE cannot process database 'MyDataBase ' because it is in use by this session. It is recommended that the master database be used when performing this operation.
Msg 3013, Level 16, State 1, Line 7
RESTORE DATABASE is terminating abnormally.
In the code above you can change the connection string corresponding to your database. Now run the application and select the server name and database name to restore the database backup file. Now click on the "Restore" Button and select the backup file location from the disk.
Restore the database from a BAK fileRight-click on the database server in the left navigation pane, click Tasks, click Restore. The name of the restoring database appears in the To database list box. To create a new database, enter its name in the list box. Select 'From device'.
I prefer to use SMO to restore a backup:
Microsoft.SqlServer.Management.Smo.Server smoServer =
new Server(new ServerConnection(server));
Database db = smoServer.Databases['MyDataBase'];
string dbPath = Path.Combine(db.PrimaryFilePath, 'MyDataBase.mdf');
string logPath = Path.Combine(db.PrimaryFilePath, 'MyDataBase_Log.ldf');
Restore restore = new Restore();
BackupDeviceItem deviceItem =
new BackupDeviceItem('d:\MyDATA.BAK', DeviceType.File);
restore.Devices.Add(deviceItem);
restore.Database = backupDatabaseTo;
restore.FileNumber = restoreFileNumber;
restore.Action = RestoreActionType.Database;
restore.ReplaceDatabase = true;
restore.SqlRestore(smoServer);
db = smoServer.Databases['MyDataBase'];
db.SetOnline();
smoServer.Refresh();
db.Refresh();
You'll need references to Microsoft.SqlServer.Smo, Microsoft.SqlServer.SmoExtended, and Microsoft.SqlServer.Management.Sdk.Sfc
Your DB connection is most likely to the database you're trying to restore. So there is a DB shared lock which prevents the restore of your db
Try this
SQL = @"USE master BACKUP DATABASE MyDataBase TO DISK='d:\MyDATA.BAK'";
Or change the connection details to use master DB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With