使用自动增量列的 DataTable.Rows.Add 上的 ConstraintException
我有一些 DataTables,其中的 ID 列在 MySQL 服务器端和 ADO.NET 架构端(从 XML 架构文件加载)都启用了自动增量。我希望在插入行时不必关心这些 ID,因为它们的唯一用途是为表提供主键 – 没有外键引用。然而,当要添加新行时,DataTable 已经包含行,即 ID 从 1 开始的行已经驻留在 DataTable 中。
ID 列的默认 AutoIncrementSeed 值为 -1,AutoIncrementStep 值为 1(仅保留 Visual Studio 提供的默认值)。如果我只想一次插入两个新行,一切似乎都很好,因为当使用 dataTable.NewRow() 创建时,它们会获得 ID -1 和 0。但是如果我想添加第三行,它会获得 ID 1 由 NewRow() 分配。随后,当我想使用 dataTable.Rows.Add(...) 插入新行时,会引发 ConstraintException,因为已经有 ID = 1 的行。
我想禁用 ADO.NET 模式的自动增量功能是没有解决方案的因为那样的话,在使用 .Rows.Add() 添加行之前,我仍然必须确保自己的 ID 是唯一的。
这个问题的简单/优雅的解决方案是什么?现在我无法想象这是一项非常不寻常的任务。
谢谢你!
I've got some DataTables with an ID column with AutoIncrement enabled both on the MySQL server side and the ADO.NET schema side (loaded from an XML schema file). I'd like not to have to care about these IDs when inserting rows because their sole use is to have a primary key for the table – there are no foreign key references. However, the DataTable will already contain rows when the new rows are to be added, i. e. rows with IDs starting from 1 already reside in the DataTable.
The default AutoIncrementSeed value for the ID column is -1 and the AutoIncrementStep value is 1 (just left the defaults provided by Visual Studio). Everything seems to be quite fine if I only want to insert two new rows at once, because when created with dataTable.NewRow() they get the IDs -1 and 0. But if I want to add a third row, it gets the ID 1 assigned by NewRow(). Subsequently a ConstraintException is thrown when I want to insert the new row with dataTable.Rows.Add(...) because there already is a row with ID = 1.
I suppose disabling the AutoIncrement stuff for the ADO.NET schema is no solution because then I would still have to make sure myself that the IDs are unique before I add the rows with .Rows.Add()
What would be an easy/elegant solution of this problem? Right now I can't imagine that this is a very uncommon task.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决此问题的一个非常简单的方法是将 AutoIncrementStep 属性也设置为 -1 - 那么 ID 将减少,即 -1、-2、-3 等。
希望这会有所帮助,
史蒂夫
A very simple way to solve this problem is set the AutoIncrementStep property to -1 as well - then the IDs will decrease ie, -1, -2, -3, etc.
Hope this helps,
Steve
您可以尝试类似于我在下面提供的示例的操作吗?在添加另一行之前,您可以使用表上的 Select 来验证唯一列值是否已存在:
Can you try something akin to the example I have provided below. You can verify whether the unique column value already exists using Select on the table before adding an another row: