如何将包含 NULL 值的列设置为 DataTable 的辅助主键

How to set a column containing NULL values as secondary primary key of a DataTable

我有一个 DataTable,其中使用 JOIN 填充了 SQL 语句。里面的DataTableIDCategory是一对唯一的,ID本身不是唯一的。

Category 允许包含 NULL 值。我想将它们设置为 DataTablePrimaryKey,以便能够使用 Find(...) 方法查找行。

但是,当我尝试将 IDCategory 设置为 DataTablePrimaryKey 属性 时,我得到 System.Data.DataException.

代码:

dt.PrimaryKey = New DataColumn() {dt.Columns.Item("ID"), dt.Columns.Item("Category")}

异常(已翻译):

Column 'Category' has null values in it

如何仍将 IDCategory 设置为 PrimaryKey

在您为 Null 列填充值之前,不允许设置主键。主键概念本身是 "NOT NULL" 列。

来自documentation

When you identify a single DataColumn as the PrimaryKey for a DataTable, the table automatically sets the AllowDBNull property of the column to false and the Unique property to true. For multiple-column primary keys, only the AllowDBNull property is automatically set to false.