4

Is there a way in Entity Framework 4.0 to bypass the object cache for a single LINQ query?

I want to be able to execute a query and know that I'm getting the absolute latest from the database even if that object has been retrieved earlier in the request and has been stored in cache.

Rob Jefferies
  • 254
  • 3
  • 9

1 Answers1

3

You must configure your query or object set to force materialization of result set instead of using already materialized entities from identity map.

context.YourObjectSet.MergeOption = MergeOption.OverwriteChanges;
// now execute the query as many times as you want

or

var query = ...;
((ObjectQuery<YourEntity>)query).MergeOption = MergeOption.OverwriteChanges;
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • +1 Good to know that. MergeOption is a somewhat unexpected name to enforce cache overrides, but ah well, it works. I was experimenting with ObjectContext.Refresh with RefreshMode.StoreWins and was baffled to see that that did _not_ work as I expected. – Gert Arnold Feb 28 '12 at 12:45
  • It did NOT work for me (EF6.0). I could not find MergeOption property. I guess there were some breaking changes in EF. This answer was useful: http://stackoverflow.com/a/4911591/1131855 – Maxim Eliseev May 23 '14 at 08:43
  • @MaximEliseev: `MergeOption` is a feature of original ObjectContext API. You are using newer API. – Ladislav Mrnka May 23 '14 at 09:48