Well, it has been a while since I blogged.  Work has been really hectic.  At the start of February we had 4 new developers start, and we have our first release coming up at the end of March.   So a lot of my time has been spent helping bring the new developers up to speed on the application, and guiding the technical direction of the project.  However, in the quiter moments, I have had the opportunity to get back into the real world and cut code.  

One of the things I seemed to spend quite a lot of time working on last week was tracking down why people where getting the dreaded unable to enforce constraints exception when populating a typed dataset.  As an aside, this error message is one of the most useless I have found in the framework!  At least tell me which constraint failed, so that I have an idea where to look.  Anyway, I think I have found the most common cause of the problem. 

  1. Ensure that you fill the dataset parents first, then it’s children.  Be careful if you have three or more tables related together, that you populate them in the order, that you would insert data into them.  For example if you have a dataset with a Contact, Address and a Contact Address relation table, that you populate the Contact table, the Address table and then the ContactAddress relation table.

  2. Remember that a key is a unique key.  If you put a key on a table, it is a unique key and data in that column must be unique.
  3. Check the data.  Ensure that the data be returned is correct.  I cannot count the number of times I have thought that the data should be correct and it wasn’t.  Also, make sure that you have the correct foreign keys and check constraints in the database to ensure that incorrect data cannot be entered in the first place.

 When trying to track down where the problem lies I normally go through the following steps. 

  1. Check the data coming back from the database and that it is in the order mentioned above.

  2. Turn enforce constraints to off.  That is on the dataset set the EnforceContraints property to false.

  3. Write the XML out of the dataset to a file and then examine it.  Turning nested relationships on also can help in you identify where problems are occurring.

  4. Check that the dataset datatable mapping is correct.  A number of times I have had found that I have had a unique key on a column that I thought was getting populated, but the table mapping was incorrect so the field wasn’t getting populated. 

  5. Check the XSD to ensure that the keyref section contains what you expect.  A number of times I have found that a developer has put on extra keys.  Most of the time this has occurred it has been on a composite key.  Unfortunately, the designer doesn’t show that there are more than one key on a attribute or element, so you don’t know it’s there.