缺少数据表中的主键

本文关键字:数据表 | 更新日期: 2023-09-27 18:00:00

当我运行以下代码从DataTable中获取值时,我得到一个错误

System.Data.dll中发生类型为"System.Data.MissingPrimaryKeyException"的异常,但未在用户代码中处理

我不知道原因和如何修复它。我得到的错误线路是

if (csvData.Rows.Find(args.BluetoothAddress.ToString()) != null)

我的完整代码:

string csv_file_path = @"C: 'Users'xxx'Desktop'xxxx.csv";
DataTable csvData;
.....
DataColumn[] primaryKeys;
primaryKeys = csvData.PrimaryKey;
.....
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
    if (args.RawSignalStrengthInDBm > -100)
    {
        if (csvData.Rows.Find(args.BluetoothAddress.ToString()) != null) 
                  // got the error
        {
            DataRow infoRow = csvData.Rows.Find(args.BluetoothAddress.ToString());
            if (infoRow[1] != null)
            {
                // Display Location information
                this.Dispatcher.Invoke((Action)(() =>
                                { textBox.Text = ("Location: "    + infoRow[2].ToString() + ", Time: " + DateTime.Now.ToString("h:mm:ss tt")).ToString(); }));
            }
            else
            {
                // record other information
                ........
            }
        }
    }
}

缺少数据表中的主键

您忘记设置应被视为数据表中主键的列或列组。以下是您的操作方法:

    DataTable csvData = new DataTable();
    DataColumn idCol = new DataColumn("Id",typeof(int));
    //column should be already added into the column list of datatable before setting it as primary key
    csvData.Columns.Add(idCol);
    //set the primary key. Here you can add multiple columns as it is a array property. This fixes your error
    csvData.PrimaryKey = new[] { idCol };
    DataColumn[] primaryKeys;
    primaryKeys = csvData.PrimaryKey;
    //if you do not set the primary key the below count was earlier coming out to be zero.
    var count = primaryKeys.Length;

MissingPrimaryKeyException在表没有主键时抛出。

为了在DataRowCollection上执行Find,您需要在DataTable上定义PrimaryKey,请尝试定义主键,如下例所示。

DataColumn column1=... ; // Table column
csvData.PrimaryKey = new DataColumn[] {column1};