【问题标题】:datatable not knowing its primary key数据表不知道其主键
【发布时间】:2010-10-14 07:50:17
【问题描述】:

我正在尝试通过查询每个列的自动增量属性来查询数据表以建立主键 [标识列]。但是它总是错误的(对于 Idenity/PK 列)。

查询表的主键集合发现数据表认为它没有PK。;

  Dim dc As DataColumn() = dt.PrimaryKey
  Debug.WriteLine(dc.Count)  'Result is 0

正在填充数据表......

Using cn As SqlConnection = MyApp.GetConnection
  Using cmd As New SqlCommand(strSQL, cn)
    Using da As New SqlDataAdapter(cmd)
      Dim ds As New DataSet
      Try
        da.Fill(ds)

        Return ds

      Catch ex As Exception
        MyAppClass.LogWarning(ex, EventLogEntryType.Error)
        Throw
      End Try
    End Using 
  End Using 
End Using

有问题的表的主键是:([myTableId] [int] IDENTITY(1,1) NOT NULL)。 及其 pk : CONSTRAINT [PK_myTablesPK] PRIMARY KEY CLUSTERED ( [myTableId] ASC )

这里有人遇到同样的问题(可能比我写的更清楚):http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/c6abdeef-0cb0-42f5-a5f1-10dc4d81df4a/

我假设我缺少一些简单的东西,有人愿意启发我吗?

【问题讨论】:

    标签: vb.net ado.net


    【解决方案1】:

    使用 fillschema 解决了我的问题;

    da.FillSchema(ds, SchemaType.Mapped, table.tableName)
    da.Fill(ds, table.tableName)
    

    DataAdapter 对象已优化 默认情况下用于只读场景。 Fill 方法只检索 需要的架构数量 填充数据集对象。获得 附加的模式是 需要更新或验证 DataSet 对象,使用其中一种 DataSet 对象的以下方法 由 数据适配器:

    • 使用 DataAdapter 的 FillSchema 方法。
    • 为 MissingSchemaAction 属性使用 AddWithKey 枚举 的 DataAdapter。

    本文介绍如何选择 当你在这两种方法之间 想要填充可更新的数据集 带有 DataAdapter 的对象。

    REF : http://support.microsoft.com/kb/310128

    【讨论】:

      【解决方案2】:

      是否需要根据自增属性确定主键?或者这对你有帮助吗?

      Private Sub GetPrimaryKeys ( myTable As DataTable )
         ' create the array for the columns.
         Dim colKeys ( ) As DataColumn = myTable.PrimaryKey
         ' get the number of elements in the array.
         Response.Write ( "Column Count: " & colKeys.Length.ToString ( ) )
         Dim i As Integer
         For i = 0 To colKeys.GetUpperBound ( 0 )
            Response.Write ( colKeys ( i ).ColumnName & _
               colKeys ( i ).DataType.ToString ( ) )
         Next i
      End Sub
      

      【讨论】:

      • 试过了,primarykey数据列集合是空的。这就是我的问题的症结所在,它是空的。 SQL 表肯定有一个有效的 PK/Identity 列。
      【解决方案3】:

      有一个库,Kailua - The forgotten methods in the ADO.NET API. ,确实为排名前 5 位的供应商提供了此元数据和其他元数据。此信息是特定于供应商的。

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 1970-01-01
        • 2015-02-18
        • 2011-07-29
        • 1970-01-01
        • 2014-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多