views:

465

answers:

2

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?

+2  A: 

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.

Josh
+2  A: 

Set DataSet.EnforceConstraints to false before filling the DataTable

TheSoftwareJedi
I'd add "before filling the dataset".
MusiGenesis
agreed, and added
TheSoftwareJedi