Sometimes when you have a big DataSet with elaborated relationships you might get the following error when trying to add or load data into the dataset:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

Some of the causes for this error are usually “regular” violations of the foreign-key constraints, which means you are referencing a certain key that does not exist in the parent table. If that is the case, you can check this article on MSDN that explains a bit on how to resolve these issues.

If you are still having problems with your dataset and ADO.NET code, you might just want to try this little trick.
It appears that inside a DataRow there is a property called RowError.

RowError is a string value that can be set or read in numerous other occasions, but the situation in which I encountered was due to a bad relationship that was added on a table which caused the code to throw an exception at runtime. In that case the RowError property hold the exact name of the troublesome relationship.

So, how do you access it?
When you code at runtime throws an exception and you are with a debugger attached, check the following thing using the “immediate window” or Quickwatch:

myDataSet.Tables["YourTableName"].Rows[0].RowError

Don’t forget to replace “myDataSet” with the variable name of your dataset and “YourTableName” with the table that is (probably) causing the problems.

In the case I’ve described above, this property told me exactly what is the problematic foreign-key that I had and from there I figured out what is the problematic relationship.

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • co.mments
  • del.icio.us
  • digg
  • Ma.gnolia
  • NewsVine
  • Reddit
  • TailRank
  • YahooMyWeb

2 Responses to “ConstraintException - A helpful tip”

  1. Ross says:

    Also, if you’re unsure which table or row is causing the error, you can inspect tables with the HasError property or the GetErrors() method:

    ds.Tables(0).HasError
    False
    ds.Tables(1).HasError
    True
    ds.Tables(1).GetErrors()(0).RowError
    ….. here’s the error ….

  2. Piektdienas krikumi - Ivara blogs says:

    [...] Savukārt, tiem, kuriem vēl nākas strādāt ar DataSetiem un saprast, kas ir par iemeslu baismajai ConstraintException, varu ieteikt izlasīt šo nelielo padomu. [...]

Leave a Reply

Login Method

OpenID

Anonymous