实体框架 - 如果 SaveChanges 失败并且我不想进行某些更改该怎么办?
我想我遇到了一个常见问题: 我想尝试将一个对象插入数据库。如果违反了主键,那么我想中止插入。 (这是一个示例,该问题确实适用于任何类型的错误和任何 CRUD 操作)
如何放弃对 EF 上下文所做的更改?
每次出现问题时我都无法重新创建它。
附言。我知道也许我可以检查一切是否正常,例如。通过查询数据库,但我不喜欢这个想法。由于某种原因存在数据库约束,这样速度更快,而且我必须编写更少的代码。
I think I'm running into a common problem:
I would like to try to insert an object to the database. If primary key is violated then I would like to abort the insert. (this is an example, the question really applies to any kind of error and any of the CRUD operations)
How can I discard changes made to EF context?
I can't afford recreating it every time something goes wrong.
PS. I know that perhaps I could check if everything is ok eg. by querying the db, but I don't like the idea. Db constraints are there for some reason and this way it's faster and I have to write less code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将插入的实体与
ObjectContext
分离。您还可以使用ObjectStateManager
及其方法GetObjectStateEntries
。在ObjectStateEntry
中,您可以修改其状态。问题是你没有以预期的方式使用技术:
当然你应该这样做,因为你的代码并不能阻止这种情况。
是的,确实您应该检查是否一切正常。调用数据库来“验证”您的数据是 DBA 真正喜欢的事情(讽刺)。您有责任在调用
SaveChanges
之前实现数据的最高有效性。我可以想象许多高级开发人员/团队领导根本不会让您的代码通过他们的代码审查。顺便说一句。在大多数情况下,由于进程间或网络通信的原因,速度并不会更快。You can detach inserted entity from
ObjectContext
. You can also useObjectStateManager
and its methodGetObjectStateEntries
. InObjectStateEntry
you can modify its state.The problem is that you are not using technology in supposed way:
Sure you should because your code doesn't prevent such situations.
Yes indeed you should check if everything is OK. Calling database to "validate" your data is something that DBAs really like (sarcasm). It is your responsibility to achieve the highest possible validity of your data before you call
SaveChanges
. I can imagine that many senior developers / team leaders would simply not pass your code through their code review. And btw. in the most cases it is not faster because of inter process or network communication.尝试使用 DbTransaction。
如果有例外
进行回滚。
Try using DbTransaction.
and if theres an exception
do a rollback.