错过数据表中的主键

时间:2016-08-03 05:18:13

标签: c#

当我运行以下代码以从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
                ........
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

当表有主键时,会抛出

MissingPrimaryKeyException

要对FindDataRowCollection DataTable DataColumn column1=... ; // Table column csvData.PrimaryKey = new DataColumn[] {column1}; getActivity() 定义android:parentActivity".YourActivityName" ,请尝试定义主键,如下例所示。

{{1}}

答案 1 :(得分:1)

您忘记设置应在数据表中视为主键的列或列组。以下是如何做到这一点:

    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;