Tuesday, 4 September 2007

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

I realise you may find other solutions for this on other blogposts but I feel I have out a bit more how to debug this very unhelpgul error. Yes it does involve check the DataTable or DataRow HasErrors. If true you then drill down the the Rows in Error and further to the columns in error through the row.

When I was debuging a certain block of my code I founf that the HasErrors did not trigger if I tried to populate my DataTable with the GetDataBy() method. BTW I am using Strongly Typed Datasets here. So for example, I declared a datatable at the top of the code:


private YourDataset.EmployeesDataTable EmployeeDT;

Then in the block where I will fill the datatable I did the following. I instantiated the datatable outside of the try catch statement. Inside the try block I attempt to populate the DataTable with the FillBy() method and then in the catch block I read whether or not the DataTable HasErrors. If it does I display the information in the exception which will then give me more direction in debugging the problem.


EmployeeDT = new YourDataset.EmployeesDataTable();
try
{
EmployeeTableAdapter.FillById(EmployeeDT,23456);




}
catch
{
String s = null;
if (EmployeeDT.HasErrors)
{
foreach (DataRow dr in EmployeeDT.GetErrors())
{
foreach (DataColumn dc in dr.GetColumnsInError())
{
s += dc.ColumnName + ",";
}
}
throw new Exception("Yes Errors Encountered, Columns in error: " + s);
}
}

Another thing on this, on my last encounter with this error it was due to me overlooking the fact that the TableAdapter field length of the a field was not long enough to accomodate a certain value which was i the database. I had stored the field length in the database as nvarchar(MAX) yet I must have neglected to update the DataSet which for that field had a MAX length of 50.

When you have your DataSet in design view or if you want to do this in code view, you can set it to AllowDBNull and when it encounters a nnull value, depending on the datatype to do one of three things: Throw and Exception, Insert Null, Or insert an empty string.

Cheers

Andrew

No comments: