我搜索了很多,但找不到解决方案。
我收到错误:
无法启用约束。一行或多行包含违反非null,唯一或外键约束的值。
我运行DataTable.GetErrors()
并看到SQL Compact Edition数据库中的某些列设置为Not NULL
。这些列在LEFT OUTER JOIN
查询中使用,因此在运行查询时它们为null。 (当我在VS中的服务器资源管理器中运行查询时,我可以得到结果)。
尝试在Datatable中加载数据时发生错误:
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;
}
}
我尝试了很多解决方案来解决这个问题,但是我无法解决这个问题。我知道“EnforceConstraints”,但由于我不使用任何数据集,我无法更改该属性。
答案 0 :(得分:4)
我设法通过获取表的模式,遍历模式表的行(它们是实际表的列)并创建与模式列具有相同属性的列来解决此问题(唯一的区别是设置新的column的AllowDBNull为true,Unique和AutoIncrement为false),最后将新列添加到新的数据表中,以后将填充我们实际表的数据(借助DataReader获取数据而不是模式)。 / p>
以下是代码:
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;
}
}