SQL Server Management Studio中有一个很有意思的工具,可以查看某个对象的依赖和被依赖关系。如下图所示
假设,我们自己的程序也要实现这样的功能,那么该怎么做呢?
1. 首先,创建一个项目,添加以下三个引用
2. 用如下代码测试
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
namespace DiscovDepedency
{
class Program
{
/// <summary>
/// 这个程序演示了如何发现数据库对象的依赖关系
/// 作者:陈希章
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Server svr = new Server("localhost");
Database db = svr.Databases["Northwind"];
Table tb = db.Tables["Orders"];
DependencyWalker walker = new DependencyWalker(svr);//这是检测关系的一个工具
//检测依赖该对象的所有其他对象
Console.WriteLine("依赖Orders表的所有对象");
DependencyTree tree = walker.DiscoverDependencies(new[] { tb }, DependencyType.Children);
foreach (var item in walker.WalkDependencies(tree))
{
var xpath = item.Urn.XPathExpression;
var type = item.Urn.Type;
Console.WriteLine("\tType:{0},Name:{1}", type, string.Format("{0}.{1}",xpath.GetAttribute("Schema",type),xpath.GetAttribute("Name",type)));
}
Console.WriteLine("Orders表所依赖的其他对象");
DependencyTree tree2 = walker.DiscoverDependencies(new[] { tb }, DependencyType.Parents);
foreach (var item in walker.WalkDependencies(tree2))
{
var xpath = item.Urn.XPathExpression;
var type = item.Urn.Type;
Console.WriteLine("\tType:{0},Name:{1}", type, string.Format("{0}.{1}", xpath.GetAttribute("Schema", type), xpath.GetAttribute("Name", type)));
}
Console.Read();
}
}
}