Hi guys,

I'm having a bit of a headache with Foreign Key Constraint

I'm using a SQL database and pulling all the foreign keys for a database with the stored procedure command

sp_fkeys <tablename>

Which is returning them all correctly
I'm then able to reference the tables and columns based on the information it returns. However when creating the relationship I'm unable to make the parent/child relationship. .Net gives the following error:

"This constraint cannot be added since ForeignKey doesn't belong to table <tablename>"

Here is an extract of the code

VB Code:
  1. cmdForeignKey.CommandText = "sp_fkeys " & CurrentTable.TableName
  2.  
  3.  'Set the reader to get the foreign key(s)
  4.  
  5. KeyReader = cmdForeignKey.ExecuteReader
  6.  
  7. While KeyReader.Read
  8. 'Set the first column to be that of the current table.
  9.        PrimaryKeyColumn = CurrentTable.Columns(Trim(KeyReader.Item("PKCOLUMN_NAME")))
  10. 'Set the second column to a row in another table
  11.        ForeignKeyColumn = DataSet.Tables(Trim(KeyReader.Item("FKTABLE_NAME"))).Columns(Trim(KeyReader.Item("FKCOLUMN_NAME")))
  12.        'Create the relationship
  13.        KeyRelationship = New ForeignKeyConstraint(PrimaryKeyColumn, ForeignKeyColumn)
  14.  
  15.        'Try to add it to the table
  16.         Try
  17.                 CurrentTable.Constraints.Add(KeyRelationship)
  18.  
  19.         Catch ex As Exception
  20.                'The error occurs when adding the constraint
  21.         End Try
  22.  
  23. End While

Now if I swap PrimaryKeyColumn and ForeignKeyColumn around no exception is generated. However, I want the PrimaryKeyColumn to be the parent of the ForeignKeyColumn. Not the other way around.

I have checked the datacolumns and they always are referencing the columns correctly. Anyone have any ideas?