从插入记录的主键检索标识值
我无法从 DataRow 中插入的记录(通过 DataAdapter.Update)检索新的标识值。
我使用强类型数据集作为 DAL。我想要更新的表与 SelectCommand 中的其他表连接,因此设计器无法自动生成插入/更新/删除命令,也无法自动“刷新数据表”(s. http://msdn.microsoft.com/de-de/library/ dex7k4dw%28v=VS.100%29.aspx)。
我尝试在主键的 DataColumn 上设置 AutoIncrement=true/false 但结果是相同的:最后一个 MAX-ID+1 而不是数据库生成的实际 ID(SQL-Server 2005 EP; pk datatype:int,是否身份:是,身份增量:1)。
如果应用程序的另一个实例插入第一个实例尚不知道的记录并因此生成已存在的 ID,则这将是错误的值 fe。
为了从数据库检索新身份,我已将以下内容附加到插入命令的 CommandText 中:
;SELECT CAST (SCOPE_IDENTITY() AS int) AS newIdRMA
此外,我还尝试将输出参数添加到其参数集合中:
这是我的代码的一部分,用于更新数据库并设置新 ID(不起作用) :
Me.dsRMA.RMA.AddRMARow(newRMA) ' adding new row to the (strong typed) DataTable '
numRowsUpdated = daRMA.Update(Me.dsRMA.RMA) ' update via DataAdapter and insert the new record in DB '
DirectCast(Page, Services).IdRma = newRMA.IdRMA ' this is not the actual value from DB but old Max-ID +1 '
编辑:
这是我的 TableAdapter 的 InsertCommand 及其参数集合的屏幕截图:
提前致谢。
i cannot retrieve the new identity value from an inserted record(via DataAdapter.Update) in my DataRow.
I'm using a strong typed Dataset as DAL. The table i want to update is joinded with other tables in the SelectCommand, hence the designer cannot automatically generate the insert-/update-/delete-commands and also it cannot "Refresh the DataTable" automatically(s. http://msdn.microsoft.com/de-de/library/dex7k4dw%28v=VS.100%29.aspx).
I've tried to set AutoIncrement=true/false on the primary-key's DataColumn but the result is the same: last MAX-ID+1 instead of the actual ID the database generated(SQL-Server 2005 EP; pk datatype:int, Is identity:yes, Identity Increment:1).
This will be the wrong value f.e if another instance of the application inserted a record that the first instance yet not knows and therefore generates an ID that already exists.
To retrieve the new identity from db i've appended following to my insert-command's CommandText:
;SELECT CAST (SCOPE_IDENTITY() AS int) AS newIdRMA
Also i've tried to add an Output-Parameter to it's parameter-collection:
This is part of my code that updates the database and sets the new ID(that doesn't work):
Me.dsRMA.RMA.AddRMARow(newRMA) ' adding new row to the (strong typed) DataTable '
numRowsUpdated = daRMA.Update(Me.dsRMA.RMA) ' update via DataAdapter and insert the new record in DB '
DirectCast(Page, Services).IdRma = newRMA.IdRMA ' this is not the actual value from DB but old Max-ID +1 '
Edit:
this is a screenshot of my TableAdapter's InsertCommand and it's parameter-collection:
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里我是如何做到的:我将以下内容附加到我的插入命令的CommandText中:
然后我将该查询的“执行模式”设置为“标量”而不是“ >NonQuery"
这样我就可以这样检索它:
Here How i do it: I append the following to my insert-command's CommandText:
Then I set the "ExecuteMode" of that Query to "Scalar" instead of "NonQuery"
so I could retrive it this way: