我正在为我的公司做一个关键的库存项目,我正面临一个我似乎无法解决的问题,这让我睡不着觉。
该应用程序旨在在单台计算机上使用,我们有例行的计算机格式化。我选择使用 localdb,因为我们已经缺少专用服务器。 我想保存/备份我的 localdb 和/或实体的数据,并确保它是防篡改的,并且能够在以后将其恢复或在需要时恢复到另一台计算机。
我尝试在连接关闭时复制 .mdf 和 .ldf 文件并在需要时恢复它们,但我不确定这是一个好方法。
最佳答案
我创建自己的 Controller
[授权(角色=“管理员”)] 公共(public)类 BackupController: Controller { 私有(private)IConfiguration配置;
public BackupController(IConfiguration config)
{
configuration = config;
}
public ContentResult Backup()
{
try
{
var filename = BackupRun();
return Content($"Backup database successfully to {filename}");
}
catch (Exception ex)
{
return Content("Backup Error database successfully: " + ex.ToString());
}
}
public IActionResult BackupAndDownload()
{
var filename = BackupRun();
var content = System.IO.File.OpenRead(filename); //NOT USE USING
var contentType = "APPLICATION/octet-stream";
var fileName = $"VideoKurs_{DateTime.Now.ToString("ddMMyyyy_HHmmss")}.bak";
return File(content, contentType, fileName);
}
public string BackupRun()
{
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
//Get Connection String
sqlcon.ConnectionString = configuration.GetConnectionString("DefaultConnection");
//Enter destination directory where backup file stored
string destdir = "E:\\Backup\\VideoKurs";
//Environment.GetEnvironmentVariable("LocalAppData") + "\\Backup" ;
//Check that directory already there otherwise create
if (!System.IO.Directory.Exists(destdir))
System.IO.Directory.CreateDirectory(destdir);
//Open connection
sqlcon.Open();
//query to take backup database
var filename = destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak";
sqlcmd = new SqlCommand("backup database [aspnet-SanSoft.Videokurs-D459F243-BB77-45A3-91E6-BD127D86F2C7] to disk='" + filename + "'", sqlcon);
sqlcmd.ExecuteNonQuery();
//Close connection
sqlcon.Close();
return filename;
}
}
关于c# - 在 C# 中使用 Entity Framework 备份 SQL Server localdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903695/