C# DataAdapter Returning 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 information about this.

Problem

During work on one application that was using C# ADO.NET DataAdapter technology to access SQL Server 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 the DataAdapter call to FillByFilename() method. But, problem was that message was broad, and I didn’t see which of the constraints is failing. So, I needed more information. Unfortunately, the library creators failed to provide more info in the exception itself, so I needed to do some more debugging.

Solution
 

Locate method itself

The first step is to locate the source code (in the designer’s auto-generated file) of that method.

Enable debugging for generated code

In Visual Studio options, disable debugging of just your code.

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.

Debug and see Errors info

Start your debugging session and check in the debugger for the results of the GetErrors() method. You will see exactly which constraint failed.

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.