Thursday, July 3, 2008

Troubleshooting Datasets

Lately I have been working a lot with strongly typed datasets, and have found that they can be difficult to troubleshoot when faced with the dreaded error message:

"Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."

After some research, I found a blog post by Roy Osherove where he had faced the same problem. In this post, Sanjay lists the following suggestion:

"Essentially, when I see the message above, I check the HasErrors property for each DataTable in the data set and then invoke the GetErrors method on the tables reporting errors. The GetErrors returns a collection of DataRows and you can invoke the .RowError property on the each of the error-stricken rows to find out just exactly what the problem is... "

His suggestion has made troubleshooting much easier. Just disable constraints on the dataset, and then write code to catch the problem once contraints are enabled. Here is a snippet of the version that I came up with:

try


{


    this.EnforceConstraints = true;


}


catch


{


     foreach(DataTable dt in this.Tables)


    {


        if (dt.HasErrors)


        {


            DataRow[] rowErrors = dt.GetErrors();


 


            for (int i = 0; i < rowErrors.GetLength(0); i++)


            {


                System.Windows.Forms.MessageBox.Show(dt.TableName + ": " + rowErrors[i].RowError.ToString());  


            }


        }


    }


}

No comments: