15 Jul C# DataAdapter returning Exception “Failed to enable constraints.”
C# DataAdapter returning Exception “Failed to enable constraints.”
We explain how to debug and get more information on the generic Exception “Failed to enable constraints.”
Abstract: Sometimes during work with DataAdapter, you get an Exception with a very broad message: “Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.” We will explain how to get more detailed, specific info.
During work on one application that was using C# ADO.NET DataAdapter technology to access SqlServer database, I started to get an exception with a very broad message: “Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.” Using Exception StackTrace, it was easy to locate the source of that exception.
It was DataAdapter call to FillByFilename() method. But, problem is that message was broad, and I didn’t see which of the constraints is failing. So, I needed more info. Unfortunately, library creators failed to provide more info in the Exception itself, so some more debugging is needed.
2.1 Locate method itself
The first step is to locate the source code (in the designer’s auto-generated file) of that method.
2.2 Enable debugging for generated code
In Visual Studio options disable debugging of just your code
2.3 Add try-catch into generated code
Add try-catch code and call to GetErrors() method to auto-generated DataAdapter code. Set a breakpoint on the catch statement.
2.4 Debug and see Errors info
Start your debugging session and check in the debugger the results of GetErrors() method. You will see exactly which constraint failed.
3 Revert generated code to normal state
Do not forget to revert your auto-generated code to a normal state. Because you are now suppressing exceptions with your catch statement. Just change something in the Designer and DataAdapter code will be auto-generated again and your debugging changes will be overwritten.