Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore SQL Server database through C# code

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.

like image 827
Gold Avatar asked Nov 18 '10 19:11

Gold


People also ask

How do you backup and restore SQL database in C#?

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.

How do I restore a SQL Server database from a BAK file?

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'.


2 Answers

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

like image 151
C-Pound Guru Avatar answered Oct 06 '22 00:10

C-Pound Guru


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

like image 27
gbn Avatar answered Oct 05 '22 23:10

gbn