备份数据库mdf&实体框架

时间:2012-02-07 19:23:02

标签: c# sql frameworks backup entity

我有一个数据库(mdf文件),我正在接近实体框架。是否可以备份MDF文件。 我已经尝试了但SMO但问题是因为我使用的是mdf文件,数据库名称为空。我已经读过它是自动生成的。

我的备份代码:

        String destinationPath = "C:\\";
        Backup sqlBackup = new Backup();

        sqlBackup.Action = BackupActionType.Database;
        sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString();
        sqlBackup.BackupSetName = "Archive";

        BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
        ServerConnection connection = new ServerConnection(".\\SQLEXPRESS");
        Server sqlServer = new Server(connection);
        StringCollection sc = new StringCollection();
        sc.Add(Environment.CurrentDirectory + "\\db\\Xmain.mdf"); //Bin directory
        sc.Add(Environment.CurrentDirectory + "\\db\\Xmain_log.ldf");
        sqlServer.AttachDatabase("Xmain", sc);
        Database db = sqlServer.Databases["Xmain"];
        sqlBackup.Initialize = true;
        sqlBackup.Checksum = true;
        sqlBackup.ContinueAfterError = true;

        sqlBackup.Devices.Add(deviceItem);
        sqlBackup.Incremental = false;

        sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
        sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

        sqlBackup.FormatMedia = false;

        sqlBackup.SqlBackup(sqlServer);

2 个答案:

答案 0 :(得分:1)

我在这里缺少一些东西,需要更多的背景,但我会咆哮一下,看看是否有什么帮助。

你的意思是实际备份文件,而不是数据吗?如果是这样,简单的答案是否定的。问题是SQL Server将在文件附加到数据库服务器时锁定该文件(在本例中为SQL Express)。您可以分离和复制然后附加,但应用程序将在此期间关闭。这也可以手动完成。

如果你想备份数据,我会考虑在SQL Server中而不是以编程方式安排它,除非你不能这样做。备份更多的是维护功能,而不是程序的一部分。

至于您的数据库名称为空,这是不可能的。事实上,您似乎正在尝试设置一个名为XMain的数据库。

答案 1 :(得分:0)

您必须在app.config中的连接字符串中设置初始目录

<add name="SalaryAndBenefitsEntities" connectionString="metadata=res://*/SalaryAndBenefitsModel.csdl|res://*/SalaryAndBenefitsModel.ssdl|res://*/SalaryAndBenefitsModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;attachdbfilename=|DataDirectory|SalaryAndBenefits.mdf;Initial Catalog=SalaryAndBenefit;user instance=true;password=ca;integrated security=SSPI;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

对于backUp请按照以下说明:
创建sql命令内容

 public string BackUpCommand(string databaseName, string fileAddress)
    {
        string command = @"BACKUP DATABASE " + databaseName + @"
                           TO DISK = '" + fileAddress + "' WITH FORMAT";
        return command;
    }

写备份方法:

public class ActionResult
{
    public bool Result { get; set; }
    public string Message { get; set; }
}
public ActionResult BackUpDatabase(string filePath)
    {
        ActionResult res = new ActionResult { Result = true };
        using (SalaryAndBenefitsEntities _context = new SalaryAndBenefitsEntities())
        {
            string command = "select db_name()";
            string databaseName = _context.Database.SqlQuery(typeof(string), command).ToListAsync().Result.FirstOrDefault().ToString();
            string backUpQuery = BackUpCommand(databaseName, filePath);
            var result = _context.Database.SqlQuery<List<string>>(backUpQuery).ToList();
            if (result.Count() > 0)
            {
                res.Result = false;
                result.ForEach(x =>
                {
                    res.Message += x.ToString();
                });
            }

            return res;
        }
    }

如果返回true数据库备份成功,否则

恢复如下:
创建sql命令内容

public string RestoreCommand(string databaseName, string fileAddress)
    {
        string command = @"use [master]
                        ALTER DATABASE  " + databaseName + @"
                        SET SINGLE_USER
                        WITH ROLLBACK IMMEDIATE
                        RESTORE DATABASE " + databaseName + @"
                        FROM  DISK = N'" + fileAddress + "'";

        return command;
    }

写入还原方法:

 public ActionResult RestoreDatabase(string filePath)
    {
        ActionResult res = new ActionResult { Result = true };
        using (SalaryAndBenefitsEntities _context = new SalaryAndBenefitsEntities())
        {
            string command = "select db_name()";
            string databaseName = _context.Database.SqlQuery(typeof(string), command).ToListAsync().Result.FirstOrDefault().ToString();
            string restoreQuery = RestoreCommand(databaseName, filePath);
            var result = _context.Database.SqlQuery<List<string>>(restoreQuery).ToList();
            if (result.Count() > 0)
            {
                res.Result = false;
                result.ForEach(x =>
                {
                    res.Message += x.ToString();
                });
            }
            return res;
        }
    }

如果返回true,则数据库恢复成功,否则

filePath 赞:C:\ Temp \ backup.bak
必须在使用此方法之前手动创建 filePath 目录(C:\ Temp)

相关问题