无法从备份文件还原数据库

时间:2013-08-26 15:51:01

标签: c# sql-server smo database-restore

根据this文章,我制作了一个小型WPF应用程序来备份/恢复数据库。

代码:

using System.Windows;
using Microsoft.SqlServer.Management.Smo;

namespace DBManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private Server srv;
        private Database db;
        private BackupDeviceItem bdi;
        private int recoverymod;

        public MainWindow()
        {
            InitializeComponent();
            srv = new Server();
            db = srv.Databases["MyDB"];
            recoverymod = (int) db.DatabaseOptions.RecoveryModel;
            bdi = new BackupDeviceItem("Test_Full_Backup1", DeviceType.File);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            BackupDB();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            RestoreDB();
        }

        public void BackupDB()
        {
            var bk = new Backup
            {
                Action = BackupActionType.Database,
                BackupSetDescription = "Full backup of MyDB",
                BackupSetName = "MyDB Backup",
                Database = "MyDB"
            };

            bk.Devices.Add(bdi);
            bk.Incremental = false;
            bk.LogTruncation = BackupTruncateLogType.Truncate;
            bk.SqlBackup(srv);
            label1.Content = "Backup finished";
            bk.Devices.Remove(bdi);
        }

        public void RestoreDB()
        {
            db.Drop();
            var rs = new Restore { NoRecovery = true };
            rs.Devices.Add(bdi);
            rs.Database = "MyDB";
            rs.SqlRestore(srv);
            label1.Content = "Restoration finished";
            db = srv.Databases["MyDB"];
            rs.Devices.Remove(bdi);
            db.RecoveryModel = (RecoveryModel) recoverymod;
        }
    }
}

当我点击button1时,会按预期创建备份文件。

当我点击button2时,我可以看到“Restoration finished”消息,一切看起来都不错,但是我无法使用另一个使用它的应用程序访问数据库。

在SQL Management Studio中,我在数据库名称后面看到“(正在恢复...)”,看起来修复过程永远不会完成。

Visual Studio 2010和SQL Server 2012

1 个答案:

答案 0 :(得分:0)

由于您指定了数据库,因此数据库处于恢复状态:

NoRecovery = true

如果要在还原后恢复数据库,请将此行更改为:

NoRecovery = false

Comparison of RECOVERY and NORECOVERY部分here中的更多信息。