Reputation: 2616
I've got a question about refreshing Entity context.
I have this method that I got out of a msdn walkthrough. It has a long running context.
protected async override void GetData()
{
ThrobberVisible = Visibility.Visible;
ObservableCollection<ProductVM> _products = new ObservableCollection<ProductVM>();
var products = await (from p in db.Products
orderby p.ProductShortName
select p).ToListAsync();
foreach (Product prod in products)
{
_products.Add(new ProductVM { IsNew = false, TheEntity = prod });
}
Products = _products;
RaisePropertyChanged("Products");
ThrobberVisible = Visibility.Collapsed;
}
It doesn't really function the way I thought it would. Let's say I run the application, without changing data application-side, I open the SQL Server database and change a value on an existing record and add a new record.
private void RefreshData()
{
GetData();
}
When I run RefreshData() I thought it would refresh the data completely, however only the new record comes through, the value on the existing record on the application-side does not get updated.
I have seen the only way to be sure that the context gets completely refreshed is to create a new context instance.
However, I'd like to understand why/what is happening. Why is the value not updated?
Upvotes: 0
Views: 43
Reputation: 169200
The DbContext
in Entity Framework automatically caches data that it retrieves from the database. You may explicitly reload the entities by calling the Reload()
method of each one of them:
foreach (Product prod in products)
{
db.Entry(prod).Reload();
_products.Add(new ProductVM { IsNew = false, TheEntity = prod });
}
...or you could disable the tracking:
var products = await (from p in db.Products
orderby p.ProductShortName
select p).AsNoTracking().ToListAsync();
More options and information are available here: http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/.
Upvotes: 1