我在下面编写了一个方法,使用反射在 .NET 应用程序中加载多个强类型数据表。如果我按如下所示运行,一切正常——包括没有抛出异常。但是,如果我改为使用注释部分(保持其他所有内容相同),那么我会收到此处描述的无法启用约束错误:enter link description here .
如果我查看错误数组中的内容,它总是如下:
"Column 'AEDelegateName' does not allow DBNull.Value."
错误的 ItemArray 看起来像这样:
[0] = {}
[1] = "Some Value"
这让我感到惊讶,因为我只希望脚本中的 1 列选择 1 列,而不是上面所示的 2 列。我还认为这很接近问题,因为其中一个似乎为空。
我的脚本没有返回 null,我可以快速直观地确认它,并在我使用的查询中说出类似 NOT NULL 的内容。
private void GetData(string query, Component tableAdapter)
{
OracleCommand command = new OracleCommand();
command.Connection = conn;
command.CommandText = query;
command.CommandType = CommandType.Text;
command.CommandTimeout = 3000;
OracleDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult);
MethodInfo[] methods = tableAdapter.GetType().GetMethods();
MethodInfo getDataMethod = tableAdapter.GetType().GetMethod("GetData");
DataTable table = (DataTable)getDataMethod.Invoke(tableAdapter, null);
Type[] paramTypes = new Type[] { table.GetType() };
MethodInfo updateMethod = tableAdapter.GetType().GetMethod("Update", paramTypes);
foreach (DataRow row in table.Rows)
{
row.Delete();
}
//try
//{
// if (reader.HasRows)
// {
// table.Load(reader, LoadOption.OverwriteChanges, FillErrorHandler);
// }
//}
//catch (Exception e)
//{
// DataRow[] errors = table.GetErrors();
//}
while (reader.Read())
{
try
{
List<object> newRow = new List<object>();
for (int i = 0; i < reader.FieldCount; ++i)
{
object currentValue = reader.GetValue(i);
Debug.WriteLine("Value: "+currentValue);
newRow.Add(currentValue);
}
table.Rows.Add(newRow.ToArray());
}
catch (ConstraintException e)
{
DataRow[] errors = table.GetErrors();
}
}
updateMethod.Invoke(tableAdapter, new object[]{table});
reader.Close();
}
最佳答案
根据 DataTable.Load Method (IDataReader, LoadOption) 的文档,我怀疑您可能遇到了以下摘录中描述的行为。您是否检查过查询返回的列数与 DataTable 上的列数?查询返回的列名是否与 DataTable 中所需的列名匹配?
Condition: The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable.
Behavior: If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. If no default value or null can be used, then the Load method throws an exception. If no specific default value has been supplied, the Load method uses the null value as the implied default value.
您在 while 循环中的代码可能正在运行,因为它没有尝试匹配架构。它只是按位置填充值,只要类型兼容、不违反约束并且数组包含的项目不多于行的列数,它就会成功。
关于c# - DataTable load() 约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15213387/