Thursday, June 30, 2005

DataTable Constraints

I'm currently developing an ADO.NET provider for a Scada system called MacroView that was first released back in 1988. Part of that development is a background service that runs on Windows, Linux, SCO Unix and Solaris. The provider creates DataTable instances as part of its implementation. The following exception occured during which caused me some confusion at first:

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

The ADO.NET provider doesn’t define any constraints and nulls are allowed by default. The debugging process eventually uncovered that one of the columns had exceeded the maximum length specification which caused the exception to be thrown by the DataTable class. Ideally the .NET DataTable constraint checking code should have a different exception message depending on the constraint failure. It would also be nice to also include the column name in the exception message text. I always try and include a reasonable amount of relevant context information in exceptions to help the fault finding process when things go wrong.