实体框架 - 保存数据时如何失败
让我们假设情况如下:我的应用程序中有一个对象上下文,我从数据库下载 15k 条记录(如 15k 份发票)。用户选择一个并对其进行一些更改。我调用 SaveChanges() 并由于某种原因失败(无论什么原因)。
现在使用的上下文无法执行任何保存,因为它无法保存这些更改。我应该做什么才能让它发挥作用?
另一种情况是我使用单独的上下文来进行更改。如果保存失败,那么什么也不会发生 - 我丢弃上下文,仅此而已。出现的问题是:如何将更改合并回主上下文? (无需再次下载15k记录)
let's suppose the situation looks like this: I have one object context in my app and I download 15k records from the db (like 15k invoices). User picks one and makes some changes to it. I call SaveChanges() and it fails for some reason (doesn't matter what reason).
Now the context that was used can't perform any save because it wasn't able to save those changes. What should I do to make it work?
Another scenario is that I use a separate context for making changes. If saving fails then nothing happens - I discard the context and that's it. The problem that arises is: how to merge changes back to the main context? (without downloading 15k records once again)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下载 15k 条记录的想法听起来很糟糕,但我们假设您必须这样做。为了使这项工作正常进行,您必须遵循的场景应如下所示:
NoTracking
方式执行查询(ObjectQuery
的MergeOption
)!它将提高性能,因为这些记录将永远不会再次在上下文中使用。Idea of downloading 15k records smells pretty bad but lets assume you must do it. The scenario you must follow to make this work should look like:
NoTracking
(MergeOption
ofObjectQuery
)! It will improve performance because these records will never be used in context again.