2013-03-04 48 views
6

我已经使用反射在.NET应用程序中加载了几个强类型的数据表,我写了一个方法。如果我按照下面的方式运行,那么一切正常 - 包括没有抛出的异常。但是,如果我使用注释部分,而不是(其他所有内容相同),那么我得到未能启用约束错误在此处描述:enter link description hereDataTable load()约束错误

如果我看看是什么错误数组里面,它总是如下:

"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(); 
} 
+0

你能描述'DataTable表'和通过'OracleDataReader'运行的查询之间的关系吗?我感觉两者的模式都不相同,DataTable.Load()覆盖了定义,从而触发了约束。 – Caramiriel 2013-03-13 21:45:35

+0

哪个'catch'块正在捕捉? – radarbob 2013-03-13 22:00:53

+0

.... @ Caramiriel可能是在正确的轨道上,但我会采取一个受过教育的WAG,并建议在行删除循环后添加'AcceptChanges()'。 – radarbob 2013-03-13 22:10:38

回答

1

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

条件:的架构兼容,但加载结果集架构包含比该数据表更少的列。

行为:如果缺少列定义了缺省值或列的数据类型是可空的,Load方法允许行是 添加,代替缺少的列的默认值或空值。 如果不能使用默认值或null,则Load方法会抛出 异常。如果没有提供特定的默认值,则加载 方法使用空值作为隐含的默认值。

您在while循环中的代码可能工作,因为它不会尝试匹配模式。它只是在位置上填充值,并且只要类型兼容,不会违反约束条件,并且该数组不包含更多的项目而不是包含行的列。