Handling of a ConstraintException

R

Ralf Hermanns

Hi.

I got so much help out of the dotnet Groups, so I thought I'd share a little
wisdom I found out.
Forgive me if the solution I present is already well known (honestly, it is
stupid simple) - But I found only questions like mine asked in the header,
and no answers.


Brief description of the problem:
You load your tables using a dataadapter into your dataset. Tables are
master/child, the dataset enforces the relation.
Somehow, one of the masters got deleted - and the children are stranded.
When enforcing the constraint, you get the exception.

You want to find out, which child rows cause the trouble. The exception does
not deliver this data in one of it's properties.


Brief description of my solution:
The data has been loaded fine already, so you can do the following (in the
catch ex as ConstraintException-block):

For each dr as DataRow in ChildTable
if dr.GetParent is Nothing then dr.delete
Next
DataAdapter.Update(ChildTable)
Dataset.EnforceConstraint = True

Now the rows causing the trouble are gone, and the changes are put back to
the database. In my solution, deleting the rows was the best idea - you
might need to do something else, but once you know the rows, you can handle
them as you like!
After Enforcing the constraint yourself, your Dataset is ready to go, as if
nothing ever happened to it!

Bye, Ralf
 
M

Miha Markic

Hi Ralf,

You might consider also setting ForeignKeyConstraint.DeleteRule to Cascade
(default) value.
If the rule is set than deleting master table it will deleta also childs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top