使用SMO DependencyWalker加载TreeView

时间:2010-07-04 16:10:14

标签: c# database dependencies smo

在Windows窗体应用程序中,使用C#我希望以编程方式将SMO DependencyWalker传递给单个对象(表,视图等),发现与该对象相关的依赖关系,然后加载WinForms TreeView,其中包含TreeView外观的结果与SQL Server 2008 Management Studio“查看依赖关系”对话框中的TreeView完全一样。一个很好的例子是使用Management Studio查看Northwind数据库中“Employees”表的依赖关系。我使用了类似下面的代码片段来开始:

UrnCollection col = new UrnCollection(); 

foreach (Table table in database.Tables) {
    if(table.Name == "Employees")
       col.Add(table.Urn); 
}

DependencyTree tree = sp.DiscoverDependencies(col, DependencyType.Children); 
DependencyWalker walker = new DependencyWalker(server); 
DependencyCollection depends = walker.WalkDependencies(tree); 

//Iterate over each table in DB in dependent order... 
foreach (DependencyCollectionNode dcn in depends)

这确实返回了我对TreeView所需的所有依赖项,但我无法看到如何迭代“depends”对象或任何其他关联的SMO对象的结果,以便我能够使用正确的父/子节点关系以正确的顺序加载TreeView节点。也许我会以错误的方式解决这个问题。有没有人能够成功地完成这样的事情?

2 个答案:

答案 0 :(得分:1)

我发布这个答案可能有助于某人正在寻找它。

DependencyCollection是一个单独的列表,因此您应该使用DependencyWalker来构建树结构。

使用FirstChild和NextSibling遍历树。

这是我的示例代码:

private void button2_Click(object sender, EventArgs e)
{
    String srvName = "xxxxxxxxxxxxx";
    String dbName = "yyyyy";
    Server srv = new Server(new ServerConnection() { ServerInstance = srvName });
    Database db = srv.Databases[dbName];

    DependencyWalker dependencyWalker = new DependencyWalker(srv);
    DependencyTree dependencyTree = dependencyWalker.DiscoverDependencies(
        new Urn[] { db.StoredProcedures["test", "dbo"].Urn }, DependencyType.Parents);

    var dep = new DependencyPrinter(dependencyTree);
    treeView1.Nodes.Clear();
    dep.PrintDependency2(treeView1);
    treeView1.ExpandAll();
}

代码正在使用此类

class DependencyPrinter
{
    private DependencyTree _dependencyTree;
    public DependencyPrinter(DependencyTree dependencyTree)
    {
        _dependencyTree = dependencyTree;
    }

    public void PrintDependency2(TreeView treeView)
    {
        var n = treeView.Nodes.Add("");
        AddToTreeNode(n, _dependencyTree.FirstChild);
    }

    private void AddToTreeNode(TreeNode treeNode, DependencyTreeNode node)
    {
        treeNode.Text = String.Format("({0}).{1}.{2}.{3}"
            , node.Urn.Type
            , node.Urn.XPathExpression.GetAttribute("Name", "Database")
            , node.Urn.XPathExpression.GetAttribute("Schema", node.Urn.Type)
            , node.Urn.XPathExpression.GetAttribute("Name", node.Urn.Type));

        if (node.FirstChild != null)
        {
            var n = treeNode.Nodes.Add("");
            AddToTreeNode(n, node.FirstChild);
        }

        if (node.NextSibling != null)
        {
            var n = treeNode.Parent.Nodes.Add("");
            AddToTreeNode(n, node.NextSibling);
        }
    }
}

答案 1 :(得分:0)

据我所知,Dependency Walker检索一个平面的对象列表 它不是递归或复合“树”结构 你必须自己建立。