开发者

Constraint Exception when copying table?

I'm experiencing some weird behavior when trying to modify some DataTable objects. Upon the second call to the subrouti开发者_开发知识库ne, I get the following error when I to copy the source DataTable to a working set:

System.Data.ConstraintException was caught Message="Column 'pk' is constrained to be unique. Value 'path0.tag0' is already present."

For context I'm defining the primary key of the data table in this chunk of code.

itemsTable.Columns.Add("pk")

For Each itemrow As DataRow In itemsTable.Rows
    itemrow.Item("pk") = itemrow.Item("path").ToString + itemrow.Item("tag")
Next

Dim keyColumns() As DataColumn = {itemsTable.Columns("pk")}
itemsTable.PrimaryKey = keyColumns

I'm then updating the table using the code in this subroutine

Private Sub DataChange(ByVal ClientHandles As Array, ByVal CurrentValues As Array, ByVal QualityValueArray() As String) _
        Handles myOpcData.DataChange

    Dim updateTable As New DataTable
    Try
        updateTable = itemsTable.Copy <-----Exception happens here

        For index As Integer = 1 To ClientHandles.Length
            updateTable.Rows(ClientHandles(index)).Item("value") = CurrentValues(index)
        Next

        itemsTable.Merge(updateTable)

    Catch ex As Exception
        Debug.Print(ex.ToString)
    End Try
End Sub

Any ideas on how to either fix my code or a suggestion if there is a better way of updating my table?


From the looks of your error it appears you are trying to add the same key into your table. What I would do is, remove all the test data from your table and then instead of the generic:

Catch ex As Exception
Debug.Print(ex.ToString)

..actually catch the primary key exception (the exception you listed above) and then do whatever. For example, if you know there will be primary key violations (i.e., you may have two of the same PK's and only want one) then just ignore the error and continue.

Make sense?


I would remove the primary key, copy the table, and then recreate it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜