C# DataAdapter returning Exception “Failed to enable constraints.”

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.

1 Problem

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.

DataAdapter 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 Solution

2.1 Locate method itself

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

DataAdapter Exception

2.2 Enable debugging for generated code

In Visual Studio options disable debugging of just your code

DataAdapter Exception

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.

DataAdapter Exception

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.

DataAdapter Exception
DataAdapter Exception

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.

No Comments

Sorry, the comment form is closed at this time.