Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. Part Two (Addendum)
Dec 21st, 2008 by ocvirek.com
I’ve just come to conclusion that there’s another annoying thing which is actually very common when working with TableAdapters, ObjectDataSource and DataBinded controls on a WebForm. For example, when you use a DataBinded DropDownList control in a DetailView control to choose one value for your ForeignKey, everything works fine, until your ForeignKey has a Null value, and there is no such value in a DropDownList. You will immidiately get this error from the title. Off course, one ObjectDataSource is used to provide DataBinding for a DetailView control, and another is used to populate your DropDownList. Regarding this other one, the best thing you can do is to create a view, stored procedure or a SELECT statement which will include a NULL value, for example:
SELECT EmployeeTypeID, EmployeeTypeDesc FROM EmpyloeeType
UNION SELECT NULL, ‘– None selected –’
and then populate DropDownList with it. But you will still get this error if your TableAdapter, which will be used for populating it, has a PrimaryKey constratint on a EmployeeTypeID field (in this example). In order to solve this, we will have to Delete this Primary Key by right clicking on the row in a TableAdapter in a DataSet designer, and then choosing Delete Key option. But still, after saving changes you will still get this error. Well I guess this is a Visual Studio’s bug rather then a feature. TableAdapter methods/queries are pretty tricky if you mess with them so make sure that always recreate them insted of trying to change them through properties. In order to do so, right click on them, choose Configure and them complete all wizard steps. In worst cases, if this doesn’t help at all, delete whole TableAdapter and then recreate new one, but this time take more care. I’ve posted this since I’ve found more complicated workarounds presented on the web, and the fact is, this is quite simple once you understood it correctly.