有没有一种纯粹的.net方法可以可靠地做到这一点?我不断找到的解决方案要么需要猜测,要么有特定于数据库提供商的解决方案。通常查询一些内部系统表来获取此信息。
每个 DataTable 对象都有一个 PrimaryKey 属性,它是表示表主键的 DataColumn 数组。
例如:
string[] GetPrimaryKeys(SqlConnection connection, string tableName)
{
using(SqlDataAdapter adapter = new SqlDataAdapter("select * from " + tableName, connection))
using(DataTable table = new DataTable(tableName))
{
return adapter
.FillSchema(table, SchemaType.Mapped)
.PrimayKey
.Select(c => c.ColumnName)
.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6096 次 |
| 最近记录: |