entity framework cache refresh
Is there an equivalent to this Rails brilliance for clearing a DB query cache in Entity Framework (any version)? I keep having this problem and can't seem to find an easy way to solve it:
All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods....
But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass true to the association call:
customer.orders # retrieves orders from the database customer.orders.size # uses the cached copy of orders customer.orders(true).empty? # discards the cached copy of orders # and goes back to the database
It is possible but those methods are not available directly on entity. You must interact with context to achieve this.
If you need to reload just single instance you can use:
If you need to reload multiple instances by single call you probably need to use ObjectContext API:
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; objectContext.Refresh(RefreshMode.StoreWins, customer.Orders);
Another approach is to run the query instead of using Refresh but that requires you to explicitly build a query to load correct orders:
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; var objectSet = objectContext.CreateObjectSet<Order>(); objectSet.MergeOption = MergeOption.OverwriteChanges; objectSet.Where(o => o.CustomerId == customer.Id).ToList();
The main differences between query and Refresh will be performance (Refresh will probably use separate query for each order in collection) and new entities (refresh reloads only entities you specify whereas query will load new as well).