如何从数据库刷新ObjectContext缓存?
我们正在从数据库加载数据:
var somethings = Context.SomethingSet.ToList();
然后有人在上下文之外删除或添加行。 Out context 仍然缓存已删除的对象,因为它不知道它们已被删除。即使我调用 Context.SomethingSet.ToList(),我们的上下文仍然包含已删除的对象,并且导航属性不正确。
从数据库刷新整个集合的最佳方法是什么?
We are loading data from db:
var somethings = Context.SomethingSet.ToList();
Then someone deletes or adds rows outside of context. Out context still has caches deleted object, because it doesn't know they were deleted. Even if I call Context.SomethingSet.ToList(), our context still contains deleted objects and navigation properties are not correct.
What is the best method to refresh whole set from database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找 Refresh 方法:
The Refresh method is what you are looking for:
EF 数据上下文是工作单元模式的实现。因此,它的设计目的不是要保留在正在完成的工作单元之外。一旦您的工作完成,您的数据上下文就会被丢弃。
这是 EF v1、EF v4 和 LINQ to SQL 的基本设计决策。除非您有非常具体的数据使用模式和大量内存,否则您应该避免将数据上下文保留的时间超过完成工作单元所需的时间。
http://sdesmedt.wordpress.com/2009/02/ 18/unit-of-work-pattern/
http://takacsot.freeblog .hu/Files/martinfowler/unitOfWork.html
The EF data context is an implementation of the Unit of Work pattern. As such, it is NOT designed to be keept around beyond the unit of work that is being done. Once your work is done, the expectation is that your data context is discarded.
This is a fundamental design decision for both EF v1, EF v4, and LINQ to SQL. Unless you have very specific data usage patterns and copious volumes of memory, you should avoid keeping your data contexts around longer than absolutely needed to complete your unit of work.
http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/
http://takacsot.freeblog.hu/Files/martinfowler/unitOfWork.html
对于虚拟属性重新加载没有帮助。它需要分离并再次加载
For virtual properties Reload doesn't help. It needs to detach and load again