如何使用smo还原SQL Server数据库而在smo中无例外

问题描述 投票:0回答:1

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

这是我的代码:

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.SmoExtended.dll中发生了Microsoft.SqlServer.Management.Smo.FailedOperationException类型的异常,但未在用户代码中处理。内部异常给我这个:无法还原到服务器'数据源= L1038 \ parvaresh;初始目录= Mainwaterphantom;集成的安全性= true

c# sql-server wpf smo
1个回答
0
投票

使用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完成备份/还原操作的资源。

退房Programming SQL Server with SQL Server Management Objects Framework

© www.soinside.com 2019 - 2024. All rights reserved.