문제

누군가에 대해 어떠한 조언을 다루는 ConstraintExceptions throw XSD datasets?

이것은 예외한 메시지:

System.Data.ConstraintException : Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
도움이 되었습니까?

해결책

의 몇 가지 팁을 했는 요즘.

  1. 그것은 훨씬 더 나은 사용이브 FillByDataXXXX()방법 대신 GetDataByXXXX()방법이기 때문에 DataTable 으로 전달을 채우 방법이 될 수 있습을 심문을 위한 힌트:

    • DataTable.GetErrors()반환합니다 의 배열을 읽어 인스턴스에서 오류
    • 읽.한 rowerror 포함 설명 행의 오류
    • 읽.GetColumnsInError()반환합니다 의 배열 DataColumn 인스턴스 류
  2. 최근에,나는 감싸는 일부를 심문하는 코드로의 서브 클래스 ConstraintException 의 끈에 대한 유용한 시작점이하여 디버깅할 수 있습니다.

C#예제에 사용:

Example.DataSet.fooDataTable table = new DataSet.fooDataTable();

try
{
    tableAdapter.Fill(table);
}
catch (ConstraintException ex)
{
    // pass the DataTable to DetailedConstraintException to get a more detailed Message property
    throw new DetailedConstraintException("error filling table", table, ex);
}

출력:

DetailedConstraintException:테이블 채우기 실패
오류보고에 대한 ConstraintExceptionHelper.데이터 집합+fooDataTable[foo]
열에 오류가:[1]
[PRODUCT_ID]-총 행 영향:1085
행 오류가 있습니다:[4]
[Column'PRODUCT_ID'입 제한합니다.값이'1'은 이미 존재합니다.] -총 행 영향:1009
[Column'PRODUCT_ID'입 제한합니다.값이"2"이 이미 존재합니다.] -총 행 영향:20
[Column'PRODUCT_ID'입 제한합니다.값이'4'은 이미 존재합니다.] -총 행 영향:34
[Column'PRODUCT_ID'입 제한합니다.값은'6'은 이미 존재합니다.] -총 행 영향:22
---->시스템입니다.데이터입니다.ConstraintException:를 사용하지 못했 제약 조건이 있습니다.하나 이상의 행 값을 포함 위반 null 이 아닌,유일한,또는 외국-키 제약 조건이 있습니다.

내가 알지 못하는 경우 이것은 너무 많은 코드를 포함한 스택에서 오버플로우 응답 그러나 여기에는 C#클래스에 가득 차있다.면책 조항:이것이 나를 위해,사용하여 주시기 바랍니다/수정합니다.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConstraintExceptionHelper
{

    /// <summary>
    /// Subclass of ConstraintException that explains row and column errors in the Message property
    /// </summary>
    public class DetailedConstraintException : ConstraintException
    {

        private const int InitialCountValue = 1;


        /// <summary>
        /// Initialises a new instance of DetailedConstraintException with the specified string and DataTable
        /// </summary>
        /// <param name="message">exception message</param>
        /// <param name="ErroredTable">DataTable in error</param>
        public DetailedConstraintException(string message, DataTable erroredTable)
            : base(message)
        {
            ErroredTable = erroredTable;
        }


        /// <summary>
        /// Initialises a new instance of DetailedConstraintException with the specified string, DataTable and inner Exception
        /// </summary>
        /// <param name="message">exception message</param>
        /// <param name="ErroredTable">DataTable in error</param>
        /// <param name="inner">the original exception</param>
        public DetailedConstraintException(string message, DataTable erroredTable, Exception inner)
            : base(message, inner)
        {
            ErroredTable = erroredTable;
        }


        private string buildErrorSummaryMessage()
        {
            if (null == ErroredTable) { return "No errored DataTable specified"; }
            if (!ErroredTable.HasErrors) { return "No Row Errors reported in DataTable=[" + ErroredTable.TableName + "]"; }

            foreach (DataRow row in ErroredTable.GetErrors())
            {
                recordColumnsInError(row);
                recordRowsInError(row);
            }

            StringBuilder sb = new StringBuilder();

            appendSummaryIntro(sb);
            appendErroredColumns(sb);
            appendRowErrors(sb);

            return sb.ToString();
        }


        private void recordColumnsInError(DataRow row)
        {
            foreach (DataColumn column in row.GetColumnsInError())
            {
                if (_erroredColumns.ContainsKey(column.ColumnName))
                {
                    _erroredColumns[column.ColumnName]++;
                    continue;
                }

                _erroredColumns.Add(column.ColumnName, InitialCountValue);
            }
        }


        private void recordRowsInError(DataRow row)
        {
            if (_rowErrors.ContainsKey(row.RowError))
            {
                _rowErrors[row.RowError]++;
                return;
            }

            _rowErrors.Add(row.RowError, InitialCountValue);
        }


        private void appendSummaryIntro(StringBuilder sb)
        {
            sb.AppendFormat("Errors reported for {1} [{2}]{0}", Environment.NewLine, ErroredTable.GetType().FullName, ErroredTable.TableName);
        }


        private void appendErroredColumns(StringBuilder sb)
        {
            sb.AppendFormat("Columns in error: [{1}]{0}", Environment.NewLine, _erroredColumns.Count);

            foreach (string columnName in _erroredColumns.Keys)
            {
                sb.AppendFormat("\t[{1}] - rows affected: {2}{0}",
                                Environment.NewLine,
                                columnName,
                                _erroredColumns[columnName]);
            }
        }


        private void appendRowErrors(StringBuilder sb)
        {
            sb.AppendFormat("Row errors: [{1}]{0}", Environment.NewLine, _rowErrors.Count);

            foreach (string rowError in _rowErrors.Keys)
            {
                sb.AppendFormat("\t[{1}] - rows affected: {2}{0}",
                                Environment.NewLine,
                                rowError,
                                _rowErrors[rowError]);
            }
        }


        /// <summary>
        /// Get the DataTable in error
        /// </summary>
        public DataTable ErroredTable
        {
            get { return _erroredTable; }
            private set { _erroredTable = value; }
        }


        /// <summary>
        /// Get the original ConstraintException message with extra error information
        /// </summary>
        public override string Message
        {
            get { return base.Message + Environment.NewLine + buildErrorSummaryMessage(); }
        }


        private readonly SortedDictionary<string, int> _rowErrors = new SortedDictionary<string, int>();
        private readonly SortedDictionary<string, int> _erroredColumns = new SortedDictionary<string, int>();
        private DataTable _erroredTable;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top