2012-01-05 89 views
2

我搜索了很多,但找不到解决方案。DataTable.Load,一行或多行包含违反非空,唯一或外键约束的值

我得到的错误:

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

我跑DataTable.GetErrors()和看到,一些列在SQL精简版数据库设置为Not NULL。这些列用于LEFT OUTER JOIN查询,因此查询运行时它们为空。 (当我在VS中的服务器资源管理器中运行查询时,我可以得到结果)。

using (SqlCeCommand Cmd = new SqlCeCommand("Query HERE", "Connection HERE")) 
       { 
        C.Open(); 
        using (SqlCeDataReader Rdr = Cmd.ExecuteReader()) 
        { 
         DataTable DT = new DataTable(); 
         DT.Load(Rdr); 
         return DT; 
        } 
       } 

我尝试了许多解决方案来克服这个,但是我没能解决这个问题:当试图加载DataTable中的数据 出现的错误。我知道“EnforceConstraints”,但因为我不使用任何数据集,我无法更改该属性。

+0

我以前通常见过很多次与返回两个DataTable关键是NULL或者没有两个数据表之间的正确连接的查询填充一个DataSet 。 – Kane 2012-01-06 11:43:15

+0

从代码中只能看到一个数据表。正如我所说,我不使用任何数据集。 – 2012-01-07 13:26:04

+0

在旧线程看到我的新答案https://stackoverflow.com/questions/7807681/getting-a-constraints-exception-when-loading-a-datareader-in-a-datatable/44533184#44533184一个简单的解决方法,至少在某些情况下适用。这个问题可能有资格作为该线程的重复,尽管两者都有重要的信息。 – SQLServerSteve 2017-06-13 23:40:20

回答

2

我设法解决这个问题,通过获取表的模式,遍历模式表的行(它们是实际表的列)并创建一个与模式列具有相同属性的列(唯一的区别是设置新列的AllowDBNull为true,Unique和AutoIncrement为false),最后将新列添加到新的数据表中,稍后将填充我们实际表的数据(通过DataReader的帮助获取数据而不是模式)。

下面是代码:

using (SqlCeConnection C = new SqlCeConnection(DBStr)) 
      using (Cmd) 
      { //using SqlCeCommand 
       Cmd.Connection = C; 
       C.Open(); 
       using (SqlCeDataReader Rdr = Cmd.ExecuteReader()) 
       { 
        //Create datatable to hold schema and data seperately 
        //Get schema of our actual table 
        DataTable DTSchema = Rdr.GetSchemaTable(); 
        DataTable DT = new DataTable(); 
        if (DTSchema != null) 
         if (DTSchema.Rows.Count > 0) 
          for (int i = 0; i < DTSchema.Rows.Count; i++) 
          { 
           //Create new column for each row in schema table 
           //Set properties that are causing errors and add it to our datatable 
           //Rows in schema table are filled with information of columns in our actual table 
           DataColumn Col = new DataColumn(DTSchema.Rows[i]["ColumnName"].ToString(), (Type)DTSchema.Rows[i]["DataType"]); 
           Col.AllowDBNull = true; 
           Col.Unique = false; 
           Col.AutoIncrement = false; 
           DT.Columns.Add(Col); 
          } 

        while (Rdr.Read()) 
        { 
         //Read data and fill it to our datatable 
         DataRow Row = DT.NewRow(); 
         for (int i = 0; i < DT.Columns.Count; i++) 
         { 
          Row[i] = Rdr[i]; 
         } 
         DT.Rows.Add(Row); 
        } 
        //This is our datatable filled with data 
        return DT; 
       } 
      } 
相关问题