How to refresh ObjectContext cache from db?

喜夏-厌秋 提交于 2019-12-18 14:46:28

问题


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?


回答1:


The Refresh method is what you are looking for:

Context.Refresh(RefreshMode.StoreWins, somethings);



回答2:


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




回答3:


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);
}


来源:https://stackoverflow.com/questions/2331225/how-to-refresh-objectcontext-cache-from-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!