[英]How can I add a new row to a table filled by an IDataReader?
I'm trying to add a new entry to a DataTable
after I load it with the info contained in an IDataReader
object, a DbDataReader
concretely. 我尝试使用包含在IDataReader
对象( DbDataReader
是DbDataReader
的信息加载DataTable
之后,向DataTable
添加新条目。 The loading goes fine and the query to the database is correct I think. 我认为加载正常,对数据库的查询是正确的。
When trying to add a new row I get an ArgumentException
with the following info: 当尝试添加新行时,我收到带有以下信息的ArgumentException
:
Cannot set column 'ID'. The value violates the MaxLength limit of this column.
This is the code I have right now: 这是我现在拥有的代码:
// Build the query:
DbCommand cmd = dbCon.CreateCommand();
cmd.CommandText = "SELECT ID, Name || ' ' || SurName AS FullName FROM Clients ORDER BY FullName;";
// Execute it:
DbDataReader reader = cmd.ExecuteReader();
// Construct the table out of the query result:
DataTable table = new DataTable();
table .Load(reader);
table.Rows.Add(0, "None");
In the database (SQLite) ID
is of type INTEGER
and both Name
and SurName
are VARCHAR
s. 在数据库(SQLite)中, ID
的类型为INTEGER
, Name
和SurName
均为VARCHAR
。 Am I doing something wrong? 难道我做错了什么? How could 0
violate the MaxLength limit? 0
如何违反MaxLength限制?
Finally you've solved the issue by using one of my favourite debugger "tricks" to un-mistify strange DataTable
exceptions. 最终,您通过使用我最喜欢的调试器“技巧”之一取消模糊了奇怪的DataTable
异常,解决了该问题。 From comments: 来自评论:
You can always look what causes the ConstraintException by using the debugger. 您始终可以使用调试器来查找导致ConstraintException的原因。 Execute table.Load(reader) in a QuickWatch Dialog Box. 在QuickWatch对话框中执行table.Load(reader)。 Afterwards execute table.GetErrors(). 然后执行table.GetErrors()。 Then you can look into the returned rows at their RowError property. 然后,您可以在返回的行的RowError属性中进行查看。 Voilà! 瞧!
Since i'm using DbDataAdapter.Fill(DataTable)
in almost all cases, i've forgotten that DataTable.Load(IDataReader)
infers the schema based on the result set from the imported IDataReader
. 由于我几乎在所有情况下都使用DbDataAdapter.Fill(DataTable)
,因此我已经忘记了DataTable.Load(IDataReader)
根据导入的IDataReader
的结果集推断架构。 But of course it needs at least one DataRow
to do so. 但是,当然,它至少需要一个DataRow
。 That was the reason why it works when the DataTable
wasn't empty. 这就是为什么在DataTable
不为空时它可以工作的原因。
Check the MaxLength property on your ID column in your datatable 检查数据表中ID列的MaxLength属性
size = dataTables(0).Columns(0).MaxLength
http://forums.asp.net/t/306971.aspx http://forums.asp.net/t/306971.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.