繁体   English   中英

如何在 smo 中毫无例外地使用 smo 恢复您的 SQL Server 数据库

[英]How restore your SQL Server database with smo without exception in smo

为什么在 WPF 中使用 SMO 还原 SQL 服务器数据库时出现异常?

这是我的代码:

ServerConnection conRestore = new ServerConnection(LaServerInstance);

Server ServerRestore = new Server(conRestore);
Restore RestoreObject = new Restore();

RestoreObject.Action = RestoreActionType.Database;
RestoreObject.Database = "Mainwaterphantom";

BackupDeviceItem source = new BackupDeviceItem(open.FileName, DeviceType.File);

RestoreObject.Devices.Add(source);
RestoreObject.ReplaceDatabase = true;

RestoreObject.SqlRestore(ServerRestore);

MessageBox.Show("Successful Restore");

我得到了这个例外:

Microsoft.SqlServer.Management.Smo.FailedOperationException 类型的异常发生在 Microsoft.SqlServer.SmoExtended.dll 中,但未在用户代码中处理。 内部异常给了我这个:恢复失败到服务器'数据源=L1038\parvaresh;初始目录=Mainwaterphantom;集成安全=true

使用 SMO 时,当出现异常时,通常最内部的异常包含您需要的信息。

为了收集所有异常文本,您必须遍历异常层次结构。

这可以通过一个小的扩展来完成,如下面的代码片段所示。

using System;
using System.Collections.Generic;

namespace Converter.Extension
{
    /// <summary>
    /// When working with SMO, when an exception arises, 
    /// usually, the most inner one contains the information that you need. 
    /// In order to collect all exception text, you have to travel through the exception hierarchy.
    /// </summary>
    public static class ExceptionExtensionMethods
    {

        public static IEnumerable<TSource> CollectThemAll<TSource>(
        this TSource source,
        Func<TSource, TSource> nextItem,
        Func<TSource, bool> canContinue)
        {
            for (var current = source; canContinue(current); current = nextItem(current))
            {
                yield return current;
            }
        }

        public static IEnumerable<TSource> CollectThemAll<TSource>(
            this TSource source,
            Func<TSource, TSource> nextItem)
            where TSource : class
        {
            return CollectThemAll(source, nextItem, s => s != null);
        }
    }

}

然后,将您的代码放入 try-catch 块并在 catch 块中收集所有文本,如下所示

catch (Exception ex)
      {


              errMessage = string.Join(Environment.NewLine + "\t", ex.CollectThemAll(ex1 => ex1.InnerException)
                    .Select(ex1 => ex1.Message));
Console.WriteLine(errMessage);
}

Internet 上有一个资源描述了如何使用 SMO 完成备份/恢复操作。

使用 SQL 服务器管理对象框架查看编程 SQL 服务器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM