针对刚刚使用 ObjectContext 插入的实体运行代码的可靠方法?
我有一些代码需要在每次将实体插入数据库时运行,问题是该代码需要实体主键。
我发现我可以使用 EntityState.Unchanged 从 ObjectStateManager 获取实体,这是插入后我的对象,但我不确定这是否始终是 ObjectContext 中唯一以“Unchanged”作为其 EntityState 的对象。
是否有一种可靠的方法来仅针对刚刚使用 ObjectContext 插入的对象运行代码?
I have some code that needs to run every time an Entity is Inserted into my database, the problem is that this code requires the Entity PrimaryKey.
I have found that I can get the Entities from the ObjectStateManager with EntityState.Unchanged and that is my object after Insert, but I am not sure if that will always be the only objects with "Unchanged" as their EntityState in the ObjectContext.
Is there a reliable way to run code only against objects that have JUST been Inserted with ObjectContext?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,有办法。您必须调用重载的
SaveChanges
,它不会在自动保存后接受更改,而是由您负责调用AcceptAllChanges
。在这种情况下,调用SaveChanges
后对象仍将处于“已添加”状态(但仅在您调用AcceptAllChanges
之前)。一般代码应如下所示:事务范围不是必需的 - 如果您发布插入代码必须在带有插入的事务中运行,这只是该方法的示例。
您还可以将该代码包装到重写的
SaveChanges
中,这样您就可以将其放在集中的位置。Yes there is a way. You must call overloaded
SaveChanges
which will not accept changes after saving automatically and instead you will be responsible for callingAcceptAllChanges
. In this scenario objects will be still in Added state after callingSaveChanges
(but only till you callAcceptAllChanges
). The general code should look like:Transaction scope is not necessary - it is just example of the approach if you post insert code must run in the transaction with insertion.
You can also wrap that code into overriden
SaveChanges
so you will have it in centralized place.