DbContext's internal caching (?)

0 votes
asked Sep 10, 2010 by darmak

I created my own context which inherits from DbContext. Let's assume I have 1 post in my [Posts] table in the database. Consider this scenario:

  1. I ask DbContext for this only post for the first time. And DbContext returns it as expected.
  2. I change one column in [Posts] table manually.
  3. I refresh my site = I ask DbContext for this post again.
  4. DbContext returns a post which has old value for this specific column!

I looked into SQL Profiler and the database IS hit every time I refresh my site, so why the returned post has an old value? I guess DbContext is trying to be very clever and has some internal caching mechanism, but it would be nice to inform me that he's so clever...

Can someone explain this to me?

1 Answer

0 votes
answered Sep 11, 2014 by greg

How are you "refreshing"? If you know a value has changed, you can Refresh the context cached value using ServerWins or ClientWins :


// Resolve the concurrency conflict by refreshing the 
// object context before re-saving changes. 
context.Refresh(RefreshMode.ClientWins, orders);

However, the real question comes down to when and why this would happen in the first place, which is related to the lifetime of the context. Perhaps you could be over-using the same context? Remember that SQL Server and etc have their own caching mechanism, and thus Entity Framework isn't the only fish in the pond of items trying to do some caching.

From, the following link we gather some tips, which if you were following, you likely wouldn't run into this problem. http://msdn.microsoft.com/en-us/data/jj729737.aspx

  • As you load more objects, memory consumption of the context may increase rapidly
  • Chances of running into concurrency related issues increases with expanded lifetime
  • When working with Web Applications, use a context instance per request
  • When working with Windows Forms, use a context per form
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter