Friday, January 9, 2009

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

I'm a coder myself. I write software programs as part of my job. You may remember situations we run into sometimes in our daily work life. Can you recall a situation you're completely stuck not knowing how to fix things esp. when writing some kind of rocket science code. Just kidding!!

I see myself in those kind of situations lot of times trying to figure out best ways to implement piece of logic. I've a weakness for fancy and flamboyant code. But, that's NOT the approach. Simple and straight forward code always helps in achieving those "bilities" like maintainability, reliability and scalability. Just keep that always in your mind.

Coming to original point, I wish for a savior who can help me in solving those weird, hard to fix, some times simple and challenging errors. I spend time googling, reading books and online help to keep things going. From my own experiences, I decided to help folks around with what i found saving their valuable time.

Let's start with what i found today. I'm trying to fill an empty data table with data from a data reader. this is how i'm doing this ..

DataTable dt = new DataTable();
dt.Load(reader);
return dt;

But, this throws an error saying " Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."

Error is understandable. But, reader contains data which is gathered from multiple tables. Importantly, i created empty data table which should be able to accept data the way it is. Whatever, point is if you happen to get same error. Try using DataTable.GetErrors() to know the exact error causing the trouble.

Or if you want to get away from this issue, try using a DataSet object and set EnableConstraints property to false. Now, Load the same data. I hope you don't see this issue.