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:
cmdForeignKey.CommandText = "sp_fkeys " & CurrentTable.TableName 'Set the reader to get the foreign key(s) KeyReader = cmdForeignKey.ExecuteReader While KeyReader.Read 'Set the first column to be that of the current table. PrimaryKeyColumn = CurrentTable.Columns(Trim(KeyReader.Item("PKCOLUMN_NAME"))) 'Set the second column to a row in another table ForeignKeyColumn = DataSet.Tables(Trim(KeyReader.Item("FKTABLE_NAME"))).Columns(Trim(KeyReader.Item("FKCOLUMN_NAME"))) 'Create the relationship KeyRelationship = New ForeignKeyConstraint(PrimaryKeyColumn, ForeignKeyColumn) 'Try to add it to the table Try CurrentTable.Constraints.Add(KeyRelationship) Catch ex As Exception 'The error occurs when adding the constraint End Try 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?




Reply With Quote