Wrapping your Hands around the Throat of EnforceConstraints

Do enforced constraints have you down?  They did for me today.  I was getting the following error as I set EnforceConstraints on a freshly filled DataSet to true.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

I found this to be annoying.  Actually, “annoying “is the polite word that I use when I find error messages to be useless in debugging.  This annoyance continued until I was pointed at this blog entry by my colleague Dave Lloyd.  Since it's his blog, it figures that he would know about it :).  It contains a code snippet can is quite handy in tracking down the source of this particular error message.  Very useful if you too need to tame the enforced constraints beast.

Comments

  • bruce May 2, 2006 3:45 PM

    I found it is very easy to get an System.Data.EnforceConstraints error from an XSD data set created in Visual Studio 2005. At first I thought it was a Null problem.

    But look at the XSD file. Right at the bottom there may be a section like this:

    <xs:unique name="Constraint1" msdata:PrimaryKey="true">
    <xs:selector xpath=".//mstns:PartSearch" />
    <xs:field xpath="mstns:PART_ID" />
    </xs:unique>

    This is enforcing a Primary Key constraint on one of the fields returned by the query. This constraint appears to have been autogenerated by Visual Studio 2005. I did not ask for it.

    However, luckily you can delete these lines from the XSD file and the query will run fine. Yes, there may be multiple records with the same value in the PART_ID field, but that is not a problem for me. It was only a problem for Visual Studio 2005.

    Watch out for autogenerated constraints. Just delete them from the XSD file.

    Good luck!

  • bruce May 3, 2006 12:47 PM

    I deleted those xml lines and still got the error

  • bruce May 4, 2006 9:26 AM

    Ok I added the following code to my error handling...

    catch (Exception ex)
    {
    DataRow [] er = t.GetErrors();
    GridView1.DataSource = er;
    GridView1.DataBind();
    }

    and found that i had exceeded the length of a field in my dataset. I find that error trapping like this also shows you the data as well as the error

  • bruce May 4, 2006 9:28 AM

    Sorry forgot to mention that "t" is a table in the dataset, and that i no longer get the error.

Leave a Comment

(required) 
(optional)
(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS