2012-02-07 11 views
1

Entity Frameworkで近づいているデータベース(mdfファイル)があります。 MDFファイルのバックアップを作成することは可能ですか? 私はすでにSMOを試しましたが、データベース名が空であるmdfファイルを使用しているため問題があります。私はそれが自動生成されていることを読んだ。私のバックアップコードのデータベースのバックアップmdfとEntity Framework

ワンピース:

 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); 

答えて

1

私はここで何かが欠けていると、より多くのコンテキストを必要とするが、私は、第二のために暴言、何が役に立つかどうかを確認しますしています。

実際にデータをバックアップするのではなく、ファイルをバックアップすることを意味しますか?もしそうなら、簡単な答えはノーです。問題は、SQL Serverがデータベースサーバーに接続されているときにファイルをロックすることです(この場合SQL Express)。デタッチしてコピーしてからアタッチすることはできますが、その間にアプリケーションがダウンします。これは手動で行うこともできます。

データをバックアップする場合は、そうしない限り、プログラムではなくSQL Server内でデータをスケジュールすることを検討します。バックアップは、プログラムの一部よりもメンテナンス機能です。

データベース名が空であるため、これは不可能です。実際には、XMainというデータベースを設定しようとしているようです。

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" /> 

を:

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

SQLコマンドのコンテンツを作成する書き込みバックアップ方式:

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; 
     } 
    } 

リターン真のデータベースのバックアップがない

他に成功した場合については、以下のフォロー復元:
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; 
     } 
    } 

復帰真のデータベースがリストアする場合であります他に成功していない

filePathように:C:の\一時\のbackup.bak
ディレクトリfilePathに
(C:\ Temp)に、この方法の使用

前に手動で作成しておく必要があります
関連する問題