views:

84

answers:

2

I'm experiencing some weird behavior when trying to modify some DataTable objects. Upon the second call to the subroutine, 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?

A: 

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?

ajdams
the DataTable.Merge function can have to functionalities. First, if the primary key is not set, it will append data. If the primary key of the table is set, then it will use the primary key to update the table, hence my confusion at this error.Also, added a 'Catch ex as ConstraintException' above the existing 'Catch ex as Exception' however, this is still a waste of cycles if the table isn't getting updated with my values.
entens
A: 

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

Joel Coehoorn