简体   繁体   中英

In C#.Net, Primary key is set for DataTable, yet exception 'Table doesn't have a primary key' is thrown

The precise exception is 'System.Data.MissingPrimaryKeyException' occurred in System.Data.dll

Additional information: Table doesn't have a primary key.

However, I have set the primary key. This is the code. Thanks.

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);

And according to msdn, this exactly how the primary key is supposed to be set- http://msdn.microsoft.com/en-us/library/system.data.datatable.primarykey.aspx

I had the same problem and PrimaryKey.Length was 0 because I was declaring the Primary keys array before I filled the DataTable with rows from the adapter. Try to fill it with data first

I don't know if this answers your question as your code does not include a DataView , it's possible that you left it out as you didn't think it was important in the example.

However, turning a table into a DataView, and then back ToTable() , removes the PrimaryKey.

I'm not 100% certain, but I believe you don't add the primary key until all of the other columns are set.

In other words move firstLinesDT.PrimaryKey = PrimaryKeyColumns; to be after the point where you add the FilePath column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM