如何向由 IDataReader 填充的表添加新行?
在使用 IDataReader
对象(具体来说是 DbDataReader
)中包含的信息加载它之后,我试图向 DataTable
添加一个新条目。我认为加载顺利并且对数据库的查询是正确的。
当尝试添加新行时,我收到一个 ArgumentException
,其中包含以下信息:
Cannot set column 'ID'. The value violates the MaxLength limit of this column.
这是我现在拥有的代码:
// 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");
在数据库(SQLite)中 ID
的类型为 < code>INTEGER 且 Name
和 SurName
都是 VARCHAR
。我做错了什么吗? 0
怎么可能违反 MaxLength 限制?
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. 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:
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. Am I doing something wrong? How could 0
violate the MaxLength limit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最后,您通过使用我最喜欢的调试器“技巧”之一来消除奇怪的
DataTable
异常,解决了该问题。来自评论:由于我正在使用
DbDataAdapter.Fill(DataTable)
< /a> 在几乎所有情况下,我都忘记了DataTable.Load(IDataReader)
根据导入的IDataReader
的结果集推断架构。当然,它至少需要一个DataRow
才能做到这一点。这就是为什么它在DataTable
不为空时起作用的原因。Finally you've solved the issue by using one of my favourite debugger "tricks" to un-mistify strange
DataTable
exceptions. From comments:Since i'm using
DbDataAdapter.Fill(DataTable)
in almost all cases, i've forgotten thatDataTable.Load(IDataReader)
infers the schema based on the result set from the importedIDataReader
. But of course it needs at least oneDataRow
to do so. That was the reason why it works when theDataTable
wasn't empty.检查数据表中 ID 列的 MaxLength 属性
http://forums.asp.net/t/ 306971.aspx
Check the MaxLength property on your ID column in your datatable
http://forums.asp.net/t/306971.aspx