How do I get Entity Framework 5 to update stale data

c#, concurrency, entity-framework

Solution

There's a Reload method in the DbEntityEntry class, so you could do:

dbContext.Entry(entity).Reload();

but that is only for one object in the context that you need to refresh from Db.

Problem

I have an EF5 WPF/MVVM solution that's working without problems. The project is an order entry system but loading an order loads lots of related items so the context is used to track all the changes and then save it off, so the context is long lived. If user A loads an order and doesn't do anything with it, and then User B loads that order and updates it I have a refresh button that was intended to let User A update the stale data. Unfortunately, I can't seem to get EF5 to ignore the cache. I originally thought this would work: ``` _trackingContext.GetObjectContext().Refresh(RefreshMode.StoreWins, theOrders); List<OrderLineItem> line_items = theOrders.SelectMany(x => x.OrderLineItems).ToList(); _trackingContext.GetObjectContext().Refresh(RefreshMode.StoreWins, line_items); ``` Where GetObjectContext() is just a wrapper ``` public ObjectContext GetObjectContext() { return (this as IObjectContextAdapter).ObjectContext; } ``` Turns out this doesn't update the data. So I thought maybe I had to change the Merge option so I added ``` var set = _trackingContext.GetObjectContext().CreateObjectSet<OrderLineItem>(); set.MergeOption = MergeOption.OverwriteChanges; ``` and I also tried it for Orders (and with the `PreserveChanges` option) but nothing worked. Eventually, I just resorted to disposing and recreating the context and then recreating the search selection but it seems like this should be overkill. Is there some easier way to just get EF5 to update any stale data with fresh data from the database? Update OK - It turns out it was a testing methodology problem. After seeing @jure's reply and implementing it, and having it appear to not work I finally got smart. I broke out SQL Profiler. The right things were happening behind the scenes but I wasn't doing the right thing to update the view. Once I did that my original code worked.

Original source

Related problems