如何获得由数据库序列生成的新对象ID? [英] How can I get the new object id generated by DB sequence?
问题描述
我有带有序列和触发器的表,因此在将其插入数据库时会创建新的ID.
I have table with sequence and trigger so it creates new id when inserting it to the DB.
在调用SaveChanges()之前如何获取新的对象ID?
How can I get the new object id, before calling SaveChanges()?
对于新对象和其他对象之间的链接,我需要此ID.
I need this id for the links between the new object and other objects.
我想在调用SaveChanges之前执行此操作,因为我希望可以选择回滚.
I want to do it before calling SaveChanges because I want to have the option to rollback.
推荐答案
不调用SaveChanges()
,就无法获得它.想一想.该ID来自数据库. SaveChanges()
是导致与DB通信的第一件事.
You can't get it without calling SaveChanges()
. Think about it. The ID comes from the DB. SaveChanges()
is the first thing which causes communication with the DB.
如果要撤消操作,可以有几种选择:
If you want to undo, you have several choices:
- 在许多情况下,插入时不需要知道客户端的ID.只需创建关系就足够了.
- 使用可由客户端生成的ID,例如GUID.
- 将
TransactionScope
用于实际"数据库事务. - 执行撤消(
DeleteObject
)而不是回滚.
- In many cases, you don't need to know the ID client-side when inserting. Simply creating the relationship is enough.
- Use a client-generateable ID like a GUID.
- Use
TransactionScope
for a "real" DB transaction. - Do an undo (
DeleteObject
) instead of a rollback.
这篇关于如何获得由数据库序列生成的新对象ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!