在C#.NET,主键设置为数据表,但例外“表没有主键”被抛出

问题描述 投票:-1回答:2

精确的例外是“System.Data.MissingPrimaryKeyException”出现在system.data.dll

其他信息:表没有主键。

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

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,主键这究竟是如何应该是SET- http://msdn.microsoft.com/en-us/library/system.data.datatable.primarykey.aspx

c# datatable primary-key datacolumn
2个回答
0
投票

我不是100%肯定,但我相信,直到所有其他列的设置您没有添加主键。

换句话说移动firstLinesDT.PrimaryKey = PrimaryKeyColumns;要在其中添加了FilePath列后点。


0
投票

为您的代码不包括DataView我不知道这是否回答你的问题,它可能是你离开它,你不认为这是在本例中很重要的。

然而,把一个表为数据视图,然后回ToTable(),删除的PrimaryKey。

© www.soinside.com 2019 - 2024. All rights reserved.