Click here to Skip to main content
15,885,546 members
Articles / General Programming / Exceptions
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
15 Jul 2022CPOL1 min read 4.1K   2  
We explain how to debug and get more information on the generic Exception “Failed to enable constraints.”
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.

Image 1

It was DataAdapter call to FillByFilename() method. But, the problem is that message was broad, and I didn’t see which of the constraints is failing. So, I needed more information. Unfortunately, library creators failed to provide more information 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.

Image 2

2.2. Enable Debugging for Generated Code

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

Image 3

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.

Image 4

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.

Image 5

Image 6

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.

History

  • 15th July, 2022: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Serbia Serbia
Mark Pelf is the pen name of just another Software Engineer from Belgrade, Serbia.
My Blog https://markpelf.com/

Comments and Discussions

 
-- There are no messages in this forum --