何时调用 Context.SaveChanges
我正在使用实体框架。我的一个实体(MyEntity)依赖于我通过执行一个存储过程获得的“密钥”,该存储过程位于 MyEntity 的范围之外(事实上,它甚至不存在于同一个上下文中,它是一个调用单独的程序集)。一旦我得到这个“密钥”,我也会执行一些其他操作(本质上是设置 MyEntity 的其他属性),然后我调用 context.SaveChanges() 来保存更改。
我的问题是...可以调用 Context.SaveChanges() 两次吗?一旦我拥有“密钥”,并在设置 MyEntity 的其他属性后再次调用?我问的原因是,一旦我有了“密钥”,我必须将它与我正在使用的当前 MyEntity 实例联系起来,否则我最终会得到重复项/孤立项。如果发生某些情况并且 MyEntity 对象的其他属性未保存,那么这不是一个致命问题。
是的,我知道,理想情况下这可以在一笔交易中完成,但我们并不总是有这种奢侈:(
谢谢!
I am using Entity Framework. One of my Entities (MyEntity) has a dependency on a "key" that I get by executing a stored proceure which lives outside of the scope of MyEntity (As a matter of fact it doesn't even exist in the same Context, its a call to a seperate assembly). once I get this "key" I perform some other actions as well (essentially setting other properties of MyEntity) then I call the context.SaveChanges() to save the changes.
My question is ... is it ok to call Context.SaveChanges() twice? Once I have the "key" and once again after I set other properties of MyEntity? The reason I ask is that once I have the "key", I must tie it with the current MyEntity instance I am working with otherwise I will end up with duplicates/orphans. And if something happens and other properties of MyEntity object are not saved, well its not a fatal issue.
Yes, I know, ideally this would be done in one transaction but we dont always have that luxury :(
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为这有什么问题。但您必须记住在第一次保存后设置
myEntity.State = EntityState.Modified
。I don't see a problem with that. But you'll have to remember to set the
myEntity.State = EntityState.Modified
after the first save.忽略您自己注意到的该系统的问题,调用 SaveChanges() 两次应该没有问题。
Ignoring the problems with this system that you yourself have noted, there should be no problem calling SaveChanges() twice.