如何查找违反约束的列

本文关键字:约束 何查找 查找 | 更新日期: 2023-09-27 18:29:01

我有一个强类型数据集,它为空值抛出这个错误,

System.Data.ConstraintException:未能启用约束。一个或更多的行包含违反非null、唯一或外键的值约束。位于的System.Data.DataTable.EnableConstraints()位于的System.Data.DataTable.EndLoadData()System.Data.Common.DataAdapter.FillFromReader(数据集数据集,DataTable数据表,字符串srcTable,DataReaderContainer数据读取器,Int32 startRecord,Int32 maxRecords,DataColumn parentSChapterColumn,对象parentSChapterValue)System.Data.Common.DataAdapter.Fill(DataTable[]dataTables,IDataReader dataReader、Int32 startRecord、Int32 maxRecords)System.Data.Common.DbDataAdapter.FillInternal(数据集数据集,DataTable[]datatables,Int32 startRecord,Int32 maxRecords,StringsrcTable、IDbCommand命令、CommandBehavior行为)System.Data.Common.DbDataAdapter.Fill(DataTable[]dataTables,Int32startRecord,Int32 maxRecords,IDbCommand命令,CommandBehaviorbehavior)在System.Data.Common.DbDataAdapter.Fill(DataTabledataTable)Fruits.DataAccess.FruitsTableAdapters.FruitsExtTableAdapters.GetFruits(字符串用户,字符串筛选器)Fruits.DataAccess.FruitsDataAccess.GetFruits(字符串用户,字符串过滤器)在Fruits.WebServices.External.Furuity.GetFruits(字符串过滤器)

所有列都填充了一行,我正在测试它,

USE [FruitDataBase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Fruits](
    [ID] [int] NOT NULL,
    [CategoryID] [int] NOT NULL,
    [Title] [nvarchar](255) NOT NULL,
    [URL] [nvarchar](255) NOT NULL,
    [Status] [nvarchar](70) NOT NULL,
    [Description] [nvarchar](1024) NULL,
    [User1] [nvarchar](50) NOT NULL,
    [Date] [datetime] NOT NULL,
    [User2] [nvarchar](50) NULL,
    [Date2] [datetime] NULL,
    [Impact] [nvarchar](255) NULL,
    [Solution] [nvarchar](1024) NULL,
 CONSTRAINT [PK_Fruits] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Fruits]  WITH CHECK ADD  CONSTRAINT [FK_Fruits_Categories] FOREIGN KEY([CategoryID])
REFERENCES [dbo].[Categories] ([ID])
GO
ALTER TABLE [dbo].[Fruits] CHECK CONSTRAINT [FK_Fruits_Categories]
GO

如何查找违反约束的列

DataSet/DataTable具有获取错误详细信息的属性。

所以这些细节本身并不像你想象的那样是例外,这就是诀窍。看见http://www.codeproject.com/Tips/405938/Debugging-DataSet-Constraint-Errors

样品:

catch (ConstraintException)
{
    DataRow[] rowErrors = this.YourDataSet.YourDataTable.GetErrors();
    System.Diagnostics.Debug.WriteLine("YourDataTable Errors:" 
        + rowErrors.Length);
    for (int i = 0; i < rowErrors.Length; i++)
    {
        System.Diagnostics.Debug.WriteLine(rowErrors[i].RowError);
        foreach (DataColumn col in rowErrors[i].GetColumnsInError())
        {
            System.Diagnostics.Debug.WriteLine(col.ColumnName 
                + ":" + rowErrors[i].GetColumnError(col));
        }
    }
}

您可以在代码中使用此方法。NET检查数据集从而抛出异常。

       public void CheckDataSet(DataSet dataSet)
       {                                                              
        Assembly assembly = Assembly.LoadFrom(@"C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework'.NETFramework'v4.0'System.Data.dll");
        Type type = assembly.GetType("System.Data.ConstraintEnumerator");
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(DataSet) });
        object instance = ctor.Invoke(new object[] { dataSet });                
        BindingFlags bf = BindingFlags.Instance | BindingFlags.Public;
        MethodInfo m_GetNext = type.GetMethod("GetNext", bf);
        while ((bool)m_GetNext.Invoke(instance, null))
        {
            bool flag = false;
            MethodInfo m_GetConstraint = type.GetMethod("GetConstraint", bf);                    
            Constraint constraint = (Constraint) m_GetConstraint.Invoke(instance, null);
            Type constraintType = constraint.GetType();
            BindingFlags bfInternal = BindingFlags.Instance | BindingFlags.NonPublic;
            MethodInfo m_IsConstraintViolated = constraintType.GetMethod("IsConstraintViolated", bfInternal);                    
            flag = (bool)m_IsConstraintViolated.Invoke(constraint, null);
            if (flag)                    
                Debug.WriteLine("Constraint violated, ConstraintName: " + constraint.ConstraintName + ", tableName: " + constraint.Table);                                            
        }
        foreach (DataTable table in dataSet.Tables)
        {
            foreach (DataColumn column in table.Columns)
            {
                Type columnType = column.GetType();
                BindingFlags bfInternal = BindingFlags.Instance | BindingFlags.NonPublic;
                bool flag = false;
                if (!column.AllowDBNull)
                {                            
                    MethodInfo m_IsNotAllowDBNullViolated = columnType.GetMethod("IsNotAllowDBNullViolated", bfInternal);                                                        
                    flag = (bool)m_IsNotAllowDBNullViolated.Invoke(column, null);
                    if (flag)
                    {
                        Debug.WriteLine("DBnull violated  --> ColumnName: " + column.ColumnName + ", tableName: " + column.Table.TableName);
                    }
                }
                if (column.MaxLength >= 0)
                {
                    MethodInfo m_IsMaxLengthViolated = columnType.GetMethod("IsMaxLengthViolated", bfInternal);                            
                    flag = (bool)m_IsMaxLengthViolated.Invoke(column, null);                            
                    if (flag)                            
                        Debug.WriteLine("MaxLength violated --> ColumnName: " + column.ColumnName + ", tableName: " + column.Table.TableName);
                }
            }
        }                                                    
}

问题是其中一个列名在数据集中不匹配,不确定是什么触发了它,但将列名与返回的列名匹配解决了问题。

我还使用了强类型数据集的"预览数据"功能,这帮助我解决了问题。

如果有人(像我目前一样)正在使用带有DataSets的VB.NET中的遗留项目来节省你们一分钟的时间,我将发布@AFract答案的VB.NET版本。希望它适合这里:

        Catch ex As ConstraintException
            Dim rowErrors = this.YourDataSet.YourDataTable.GetErrors()
            System.Diagnostics.Debug.WriteLine("YourDataTable Errors:" & rowErrors.Length)
            For i = 0 To rowErrors.Length - 1
                For Each col As DataColumn In rowErrors(i).GetColumnsInError()
                    System.Diagnostics.Debug.WriteLine(col.ColumnName & ":" & rowErrors(i).GetColumnError(col))
                Next
            Next
        End Try