conn.GetSchema 找到 table 的主键 - MsAccess

conn.GetSchema find primary key of table - MsAccess

我有一个 MsAccess 数据库 (.mdb) 位于 D 盘 (D:\project.mdb)。 数据库有超过 120 个表。有一个 table Records 有主键和多个字段。我想获取 Columns、ColumnType 和 PrimaryKey。

我正在使用以下方法获取字段及其类型:

Dim TableNm_ As String = "Records"      
Dim restrictions2() As String = {Nothing, Nothing, TableNm_, Nothing} 
Dim DataTable2 As System.Data.DataTable = conn.GetSchema("Columns", restrictions2)

但是没有PrimayKey列。

我浏览了几篇 SO 帖子和其他帖子,例如 GetSchema and PrimaryKey column。但是我不想创建命令和Reader读取密钥。

有什么方法可以使用 conn.GetSchema 获取 table Records 的 PrimayKey 列吗?

您可以使用 Connection.GetOleDbSchemaTable 并传递 PrimaryKeys SchemaGuid。 对 TableName 应用限制为:

DataTable2 = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, New String() {Nothing, Nothing, TableNm_}) 
For Each TableRow As DataRow In DataTable2.Rows
    If TableRow.Item("PK_NAME").ToString.ToLower = "PrimaryKey".ToLower Then
        Dim  PrimaryKey = TableRow.Item("COLUMN_NAME")
        Dim Ordinal = CShort(TableRow.Item("ORDINAL"))
    End If
Next

您可以使用 Kros.Utils.MsAccess

中的 DatabaseSchema
using(var cn = new OleDbConnection("MS Access Connection String"))
{  
  DatabaseSchema schema = DatabaseSchemaLoader.Default.LoadSchema(cn);
  Assert.IsFalse(schema.Tables["Person"].Columns["Id"].AllowNull);
}

包含有关表、列、索引...的信息...