Search code examples
sql-serverasp.net-mvcdatabase-restore

Restore database from backup in asp mvc


i am new in asp mvc and i am trying to make actions that backup database and restore it from the backup file

here the code

public class BackupController : Controller
{
    private RemasEntities1 db = new RemasEntities1();
    // GET: Backup
    public ActionResult BackupDatabase()
    {
        string dbPath = Server.MapPath("~/App_Data/DBBackup.bak");
        using (var db = new RemasEntities1())
        {
            var cmd = String.Format("BACKUP DATABASE {0} TO DISK='{1}' WITH FORMAT, MEDIANAME='DbBackups', MEDIADESCRIPTION='Media set for {0} database';"
                , "Remas", dbPath);
            db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, cmd);
        }
        return new FilePathResult(dbPath, "application/octet-stream");
    }

   
    public ActionResult RestoreDatabase()
    {
        string dbPath = Server.MapPath("~/App_Data/DBBackup.bak");
        using (var db = new RemasEntities1())
        {

            var cmd = String.Format("restore DATABASE {0} from DISK='{1}';"
                , "Remas", dbPath);
            db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, cmd);
        }
        return View();
    }
}

the backup action works good, but when i try to restore database from restore action, it throw an exception

An exception of type sql.data.sqlexception' occured in entityframework.sqlserver.dll but was not handled in user code

Restore cannot process database 'Remas' because it is in use by this session. It is recommended that the master database be used when performing this operation


Solution

  • Try using master:

    var cmd = String.Format("USE master restore DATABASE Remas from DISK='{0}' WITH REPLACE;", dbPath);