C# 如何从数据库刷新 ObjectContext 缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2331225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh ObjectContext cache from db?
提问by LukLed
We are loading data from db:
我们正在从 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.
然后有人删除或添加上下文之外的行。Out 上下文仍然缓存了已删除的对象,因为它不知道它们已被删除。即使我调用 Context.SomethingSet.ToList(),我们的上下文仍然包含已删除的对象并且导航属性不正确。
What is the best method to refresh whole set from database?
从数据库刷新整个集合的最佳方法是什么?
采纳答案by Josh
回答by jrista
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.
EF 数据上下文是工作单元模式的实现。因此,它的设计目的不是为了超出正在完成的工作单元。一旦您的工作完成,您的数据上下文就会被丢弃。
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.
这是 EF v1、EF v4 和 LINQ to SQL 的基本设计决策。除非您有非常具体的数据使用模式和大量内存,否则您应该避免将数据上下文保留的时间超过完成工作单元绝对需要的时间。
http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/
http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/
http://takacsot.freeblog.hu/Files/martinfowler/unitOfWork.html
http://takacsot.freeblog.hu/Files/martinfowler/unitOfWork.html
回答by rnofenko
For virtual properties Reload doesn't help. It needs to detach and load again
对于虚拟属性,重新加载无济于事。它需要分离并重新加载
public T Reload<T>(T entity) where T : class, IEntityId
{
((IObjectContextAdapter)_dbContext).ObjectContext.Detach(entity);
return _dbContext.Set<T>().FirstOrDefault(x => x.Id == entity.Id);
}