简体   繁体   中英

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?

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.

MSDN has a FAQ .

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) .

To use this example, reference the Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc and 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);       
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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