I have implemented what you suggest in your very useful post but I am experiencing a bug that I am having problems understanding and satisfactorily resolving.
It goes something like this:
I have a parent table and a child table with a foreign key relationship between them. They are in a SQL Server 2K database and are defined also in a strongly typed dataset. Cascading is set to happen in the dataset and the database.
I update the parent table and then I attempt to update the child table (in fact it is the added rows part that is attempted). On attempting this I get the following error: "INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_Child_Parent'. The conflict occurred in database 'Tests', table 'Parent', column 'ParentID'.\r\nThe statement has been terminated."
Now when investigating this in the Immediate Window I found that if I examined the contents of the row which the command was attempting to insert the new (positive) ID assigned by the database was in place correctly in both the Parent table and the Child table. This confused me greatly as I could see no reason given this why their might be a conflict. I ran a Profiler trace using SQL Profiler and saw that the Update command was passing the original (negative) ID for the Parent row when trying to insert the row for the child.
I am having real problems trying to reconcile why the dataset should show that the fkID is the new fkID whilst the TableAdapter.Update command should be using the old fkID.
I didn't leave my investigating there however but looked at the row which the ChildTable.Select("","", DataViewRowState.Added)) was referencing (obviously I thought it should be the same row, but just out of interest. What I found when I tried "((DataRow)(ChildTable.Select("","",DataViewRowState.Added))[0])" in the Immediate Window was that the row contained the error I was experiencing. I used the DataRow.ClearErrors() method to clear the error and the tried the DataRow.EndEdit() method. When I then retried the line of code (pressed F5) was that it inserted fine.
I don't want to have to iterate through each row in the child to call the EndEdit() method and I'm sure I'm missing what is probably a simple trick. I hope that you (or someone) can help me.
Many Thanks,
Neil.
Developer |