16

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?

3 Answers 3

19

The Refresh method is what you are looking for:

Context.Refresh(RefreshMode.StoreWins, somethings);
Sign up to request clarification or add additional context in comments.

1 Comment

I changed question a little. I have to call Context.Refresh(RefreshMode.StoreWins, somethings) first and var somethings = Context.SomethingSet.ToList() to get added rows, because refresh won't add them. I just noticed in profiler that refresh goes in one query, so performance is quite good. Thanks.
12

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

2 Comments

I knew that someone will give that answer:) Don't worry. I use one ObjectContext per request, but I have one context that is used to cache some data. It is used only for reading. But it is good you noticed.
Well, glad you are disposing of your contexts. :D I can't count anymore how often I see people trying to keep their object contexts around forever. They are trying to solve one perceived problem (an assumed performance hit), while at the same time they create a dozen more worse problems that also hurt performance even more in the long run. I try to crush that behavior whenever I encounter it. ;P
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.