问题
I was trying to add a new row to the database using the below code.
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()
The design of the Rundef
table:
回答1:
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.
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.
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.
来源:https://stackoverflow.com/questions/51763617/auto-increment-primary-key-value-is-always-0