DbContext's internal caching (?)
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:
- I ask DbContext for this only post for the first time. And DbContext returns it as expect开发者_JAVA百科ed.
- I change one column in [Posts] table manually.
- I refresh my site = I ask DbContext for this post again.
- 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?
How are you "refreshing"? If you know a value has changed, you can Refresh the context cached value using ServerWins or ClientWins :
http://msdn.microsoft.com/en-us/library/vstudio/bb738618(v=vs.100).aspx
// 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
精彩评论