Wer*_*ght 2 c# sql-server datatable schema foreign-key-relationship
我需要获取列名,主键,外键和其他架构信息.这DataTable
堂课似乎包含了所有这些.
下面是我到目前为止的当前代码.有了它,我可以检索除外键之外的所有信息.我期待它们被定义,DataTable.Constraints
但它们不是.这是我目前的代码:
private static DataTable LoadSchemaInfo(string tableName, SqlConnection connection)
{
string cmdText = "SELECT * FROM [" + tableName + "] WHERE 1 = 0";
// Create a SqlDataAdapter to get the results as DataTable
var sqlDataAdapter = new SqlDataAdapter(cmdText, connection);
// Create a new DataTable
var dataTable = new DataTable(tableName);
// Fill the DataTable with the result of the SQL statement
sqlDataAdapter.FillSchema(dataTable, SchemaType.Source);
return dataTable;
}
Run Code Online (Sandbox Code Playgroud)
知道如何检索所有信息或如何获取FK(最好不使用纯SQL语法,因为我会缺少一些编译时检查)?
使用SMO你可以做到这一点......
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Agent;
// Add references: (in c:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\)
// Microsoft SqlServer.ConnectionInfo
// Microsoft SqlServer.Management.Sdk.Sfc
// Microsoft SqlServer.Smo
namespace SMO
{
class Program
{
static Database db;
static void Main(string[] args)
{
Microsoft.SqlServer.Management.Smo.Server server;
SqlConnection sqlConnection = new SqlConnection(@"Integrated Security=SSPI; Data Source=LOCAL");
//build a "serverConnection" with the information of the "sqlConnection"
Microsoft.SqlServer.Management.Common.ServerConnection serverConnection =
new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
//The "serverConnection is used in the ctor of the Server.
server = new Server(serverConnection);
db = server.Databases["TestDB"];
Table tbl;
tbl = db.Tables["Sales"];
foreach (ForeignKey fk in tbl.ForeignKeys)
{
Console.WriteLine("Foreign key {0} references table {1} and key {2}", fk.Name, fk.ReferencedTable, fk.ReferencedKey);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12706 次 |
最近记录: |