如何使用实体框架在asp.net应用程序中备份和恢复本地数据库?

时间:2014-06-26 12:40:14

标签: asp.net sql-server entity-framework

我想为ASP.Net WebApplication添加一个简单的备份和还原选项。我在我的数据库中创建了以下过程:

CREATE PROCEDURE dbo.[BackUp]
    @path NVARCHAR(MAX)
AS 
    DECLARE @DataBaseName NVARCHAR(MAX)  = DB_NAME()

    BACKUP DATABASE @DataBaseName
    TO DISK = @path
    WITH FORMAT,
    MEDIANAME = 'Backup'
GO

我使用实体框架创建了我的模型。程序是:

public virtual int BackUp(string path)
{
    var pathParameter = path != null ?
    new ObjectParameter("path", path) :
    new ObjectParameter("path", typeof(string));
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("BackUp", pathParameter);
}

但是当我拨打Backup时,我看到了这个错误:

无法在事务中执行备份或还原操作。 BACKUP DATABASE异常终止。

enter image description here

1 个答案:

答案 0 :(得分:2)

我通过将Backup函数更改为此来解决了这个问题:

public void BackUp()
    {

        Kimiakesht entity = new Kimiakesht();
        string dataTime = DateTime.Now.ToString("yyyy-MM-dd") + "-" + DateTime.Now.ToString("HH-mm");
        string directory = HttpContext.Current.Server.MapPath("~/") + "/backups/" + dataTime + "/";
        string fileName = directory + dataTime + ".bak";

        #region Response
        HttpResponse Response = HttpContext.Current.Response;
        Response.Clear();
        Response.BufferOutput = false;
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "inline; filename=\"" + dataTime + "\".zip");
        #endregion

        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);


        // Here the procedure is called and executes successfully
        entity.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, "EXEC [dbo].[BackUp] @path = N'" + fileName + "'");

        #region Compress
        using (var memoryStream = new System.IO.MemoryStream())
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                zip.ParallelDeflateThreshold = -1;
                zip.AddDirectory(directory);
                zip.Save(memoryStream);
            }

            memoryStream.Position = 0;
            var b = new byte[1024];
            int n;
            while ((n = memoryStream.Read(b, 0, b.Length)) > 0)
                Response.OutputStream.Write(b, 0, n);
        }
        #endregion

        Directory.Delete(directory, true);

        Response.Close();
    }

此功能从数据库创建备份,压缩它,然后将其作为HttpResponse返回下载。最后删除临时目录

<强>更新

这是stored procedure内容:

ALTER PROCEDURE [dbo].[BackUp]
    @path NVARCHAR(MAX)
AS 
    DECLARE @DataBaseName NVARCHAR(MAX)  = DB_NAME()

    BACKUP DATABASE @DataBaseName
    TO DISK = @path
    WITH FORMAT,
    MEDIANAME = 'Z_SQLServerBackups'