2014-06-26 54 views
1

我想爲我的ASP.Net WebApplication添加一個簡單的備份和恢復選項。我創建了下面的步驟在我的數據庫:如何使用實體框架在asp.net應用程序中備份和恢復本地數據庫?

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

+0

有什麼不清楚的錯誤消息? – usr

+0

我不知道那個錯誤信息的含義是什麼,我該如何解決這個問題! –

+1

似乎有點清楚。您有一個事務處於打開狀態,並且BACKUP語句不能在事務下運行。找出誰開了那筆交易。 – usr

回答

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。最後,刪除臨時目錄

UPDATE

這是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' 
+0

不錯的解決方案。你能解釋你如何在SQL和示例代碼上製作存儲過程嗎?感謝 – pixparker

+1

@pixparker,答案已更新。 –