【发布时间】:2011-04-25 22:21:12
【问题描述】:
我需要获取列名、主键、外键和其他架构信息。 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;
}
知道如何检索所有信息或如何获取 FK(最好不使用纯 SQL 语法,因为这样我会缺少一些编译时检查)?
【问题讨论】:
标签: c# sql-server datatable schema foreign-key-relationship