Can calling ToList on a DbSet cause caching?

caching entity-framework entity-framework-6 sqldependency

Question

I was using the following code to repopulate an ObservableCollection<T> on change notification from a SqlDependency:

var set = _dbContext.Set<T>().ToList();
this.AddRange(set);

In this scenario, the OnChange event fires correctly, but the list is repopulated with the same contents as before. Now I am using the following, second DbContext to populate the list as follows, and now the list is always up to date after a change:

using (var dbContext = new XTimeDbContext())
{
    var set = dbContext.Set<T>().ToList();
    this.AddRange(set);
}

The only difference I can imagine is that the first method's query results are cached. If so, how can I prevent this? If not, why is the list not properly updated?

Accepted Answer

Use the AsNoTracking() method (here) to prevent entities from being cached:

var set = _dbContext
    .Set<T>()
    .AsNoTracking()
    .ToList();

this.AddRange(set);



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why