0

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?

ProfK
  • 44,292
  • 106
  • 358
  • 713
  • Did you have a look à [this one](http://stackoverflow.com/questions/5799737/entity-framework-4-1-dbset-reload)? Seems to be a similar pb, it might help. – MaxSC Nov 28 '13 at 14:21

1 Answers1

1

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

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

this.AddRange(set);
qujck
  • 13,744
  • 4
  • 40
  • 70
  • 1
    as I pointed out in my question, I don't get caching when I use `using (var dbContext = new XTimeDbContext())`, only when I use the class level `_dbContext`, but `var set = _dbContext.Set.AsNoTracking().ToList();` `this.AddRange(set);` works a treat, thanks. – ProfK Nov 29 '13 at 05:10