简体   繁体   English

检索SQL Server数据库架构和对象并反映在.Net应用程序中

[英]Retrieving SQL Server database schema and objects and reflect in a .Net application

What is the simplest way to reflect the SQL Server database schema with all its objects in a .Net application? 在.Net应用程序中将SQL Server数据库架构及其所有对象反映出来的最简单方法是什么?

Basically I would like my application to scan the database schema and present me all tables and other objects. 基本上,我希望我的应用程序扫描数据库架构并向我展示所有表和其他对象。 Further I should be able to explore all table columns and their properties (type, constraints, etc.) as well. 此外,我还应该能够探索所有表列及其属性(类型,约束等)。

I am planning to use Data Access Application Block for my data access needs. 我打算使用数据访问应用程序块来满足我的数据访问需求。 Would it also meet the above stated requirement? 是否也符合上述规定?

You can use any data access method you want - you just need to run the right queries on the database. 您可以使用所需的任何数据访问方法-您只需要在数据库上运行正确的查询即可。 This article seems to have a good example of what you want. 本文似乎是您想要的一个很好的例子。

SQL Server provides some system views that can be used, eg sys.tables lists all tables, sys.columns all columns etc. SQL Server提供了一些可以使用的系统视图,例如sys.tables列出所有表, sys.columns所有列等。

MSDN has a FAQ . MSDN有一个常见问题解答

Although you can use queries on the metadata tables of SQL Server, the cleanest way to access this information is by using Sql Server Management Objects (SMO) . 尽管可以在SQL Server的元数据表上使用查询,但是访问此信息的最简单方法是使用Sql Server管理对象(SMO)

To use this example, reference the Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc and Microsoft.SqlServer.Smo. 若要使用此示例,请参考Microsoft.SqlServer.ConnectionInfo,Microsoft.SqlServer.Management.Sdk.Sfc和Microsoft.SqlServer.Smo。

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

   var sqlConnection = new SqlConnection(@"Data Source=(local);Integrated Security=SSPI");
    var server = new Server(new ServerConnection(sqlConnection));

    foreach (Database database in server.Databases)
    {
        foreach (Table table in database.Tables)
        {
            Console.WriteLine("{0}: {1}", database.Name, table.Name);       
        }
    }

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

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