问题描述
我正尝试使用以下代码向数据库添加新行.
I was trying to add a new row to the database using the below code.
即使Rundef
表具有应自动递增的主键,其值始终为零.为什么会这样?
Even though the Rundef
table has a primary key that should auto increment, it's value is always zero. Why does this happen?
Private oRunDefDS As DataSet
Dim oDR As DataRow = oRunDefDS.Tables("RunDef").NewRow()
Rundef
表的设计:
推荐答案
在代码中创建新行时,尚未将其插入数据库中.这意味着数据库引擎尚未分配其增量ID,而是将其默认设置为0.
When you create a new row in code it hasn't been inserted into the database yet. This means the database engine hasn't assigned it's incremental ID and gives it a default of 0 instead.
将记录插入数据库,并且ID应该自动更新,尽管您可能还需要重新读取该行以取回数据,具体取决于您使用的数据访问方式.
Insert the record to the database and the id should be updated automatically, though you might need to re-read the row to get the data back depending on the data access too you are using.
如果不是这种情况,那么您的代码可以创建许多新行,仅供内部使用,但是需要对所使用的ID进行保留.如果您从未将这些新行保存到数据库中,您的增量ID最终将有很多空白.
If this were not the case then your code could create many new rows for internal use only, but there would need to be a reservation on the IDs used. If you never saved these new row to the database you would end up with lots of gaps in your incremental IDs.
这篇关于自动递增主键值始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!