0

确切的异常是 System.Data.dll 中发生的“System.Data.MissingPrimaryKeyException”

附加信息:表没有主键。

但是,我已经设置了主键。这是代码。谢谢。

DataColumn[] PrimaryKeyColumns; //Global
DataTable firstLinesDT = new DataTable();
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "FirstLines";
column.Unique = true;
firstLinesDT.Columns.Add(column);

PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = column;
firstLinesDT.PrimaryKey = PrimaryKeyColumns;  

column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Length";
firstLinesDT.Columns.Add(column);

column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "FilePath";
firstLinesDT.Columns.Add(column);

**// EXCEPTION THROWN AT FIND OPERATION** 
DataRow foundRow = firstLinesDT.NewRow();
foundRow = firstLinesDT.Rows.Find(line);

根据 msdn,这正是应该设置主键的方式 - http://msdn.microsoft.com/en-us/library/system.data.datatable.primarykey.aspx

4

3 回答 3

1

我遇到了同样的问题,PrimaryKey.Length 为 0,因为我在填充DataTable来自适配器的行之前声明了主键数组。尝试先用数据填充它

于 2019-10-24T13:16:41.007 回答
0

我不是 100% 确定,但我相信在设置所有其他列之前不要添加主键。

换句话说,移动firstLinesDT.PrimaryKey = PrimaryKeyColumns;到添加FilePath列的点之后。

于 2011-11-21T22:24:20.157 回答
0

我不知道这是否回答了您的问题,因为您的代码不包含 a DataView,您可能将其遗漏了,因为您认为它在示例中并不重要。

但是,将表转换为 DataView,然后再返回ToTable(),会删除 PrimaryKey。

于 2016-09-18T18:08:58.883 回答