DataTable load()约束错误

sci*_*ket 6 .net c# database oracle datatable

我在下面编写了一个方法,使用反射在.NET应用程序中加载几个强类型的数据表.如果我按原样运行,一切正常 - 包括没有抛出异常.但是如果我使用注释部分(保持其他所有内容相同),那么我将无法启用此处描述的约束错误:在此处输入链接描述.

如果我查看errors数组中的内容,它总是如下:

"Column 'AEDelegateName' does not allow DBNull.Value."
Run Code Online (Sandbox Code Playgroud)

并且错误的ItemArray将类似于:

[0] = {}
[1] = "Some Value"
Run Code Online (Sandbox Code Playgroud)

这让我感到惊讶,因为我只希望脚本中的一列选择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();
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*See 1

根据DataTable.Load Method (IDataReader, LoadOption)的文档,我怀疑您可能会遇到下面摘录中描述的行为。您是否检查了查询返回的列数与数据表上的列数?查询返回的列名是否与数据表中所需的列名匹配?

条件:架构兼容,但加载的结果集架构包含的列少于 DataTable。

行为: 如果缺失列定义了默认值或者该列的数据类型可为空,则 Load 方法允许添加行,用默认值或空值替换缺失列。如果不能使用默认值或 null,则 Load 方法将引发异常。如果未提供特定的默认值,则 Load 方法将使用 null 值作为隐含的默认值。

while 循环中的代码可能正在工作,因为它没有尝试匹配架构。它只是按位置填充值,并且只要类型兼容、不违反约束并且数组包含的项目数不超过行的列数,就会成功。