Reputation: 406
I am getting this error but only very occasionally. 99.9% of the time it works fine:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Does anyone have any idea on what the cause could be? I only use that datatable for viewing and not updating so is it possible to easily turn off all constraints somehow?
Upvotes: 2
Views: 3502
Reputation: 3950
This error can also present if you're using an XSD DataSet to define your schema and the maximum length of a variable-length field (varchar, varbinary, etc) is increased in the database but the XSD is not regenerated.
In my case, I had a varchar(100)
database field with a text value 60 characters in length. The XSD expected this field to have a maximum length of 50 (you can see this in the InitClass()
method of the Designer.cs file). When this record was loaded I received the "Failed to enable constraints" error message. Updating the record to reduce the field below 50 removed the error.
Upvotes: 0
Reputation: 35196
Set DataSet.EnforceConstraints to false before filling the DataTable
Upvotes: 3
Reputation: 44906
This typically happens when the schema on your dataset is enforcing something that your database is not.
Visual Studio will automatically read schema and try and set up some primary keys on your dataset, but if you are using a view that can possibly return multiple rows it will fail. It is easy enough to remove these constraints from the DataSet itself by deleting the constraint in the designer.
Check to ensure that your dataset is not enforcing a primary key in a situation where you could possibly have two rows with the same key, like in a View that joins two tables together and therefore duplicates the rows in the parent table. VS by default will try and create the primary key of the parent table as a unique constraint on the dataset, but the view itself enforces no such constraint.
Upvotes: 2