我是asp mvc的新手,我正在尝试制作备份数据库并从备份文件中恢复它的操作
这里是代码
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();
}
}
备份操作运行良好,但是当我尝试从还原操作还原数据库时,它会抛出异常
sql.data.sqlexception类型的例外'发生在entityframework.sqlserver.dll中但未在用户代码中处理
还原无法处理数据库' Remas'因为它在本次会议中使用。建议在执行此操作时使用master数据库
答案 0 :(得分:0)
尝试使用master
:
var cmd = String.Format("USE master restore DATABASE Remas from DISK='{0}' WITH REPLACE;", dbPath);