How to Refresh DbContext

Mohsen picture Mohsen · Aug 11, 2013 · Viewed 60.2k times · Source

I want to refresh all entities of my DbContext without recreating it, I tried the following and none of them make sense:

var context = ((IObjectContextAdapter)myDbContext).ObjectContext;

var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(
                                   EntityState.Added
                                   | EntityState.Deleted
                                   | EntityState.Modified
                                   | EntityState.Unchanged)
                          where entry.EntityKey != null
                          select entry.Entity);

context.Refresh(RefreshMode.StoreWins, refreshableObjects);
//.......................................................................
foreach (var entry in this.Orm.ChangeTracker.Entries())
{
    entry.State = EntityState.Unchanged;
}
this.Orm.ChangeTracker.DetectChanges();

And the only one which refreshes my DbContext:

foreach (var i in this.Orm.ChangeTracker.Entries())
    i.Reload();

But it's too slow. Can you help me choosing the right way?

Answer

Mohsen picture Mohsen · Aug 11, 2013

I just found that the Enumerable result should be evaluated because the Refresh method gets it as object and doesn't evaluate it.

var context = ((IObjectContextAdapter)myDbContext).ObjectContext;
var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(
                                           EntityState.Added
                                           | EntityState.Deleted
                                           | EntityState.Modified
                                           | EntityState.Unchanged)
                          where entry.EntityKey != null
                          select entry.Entity).ToList();

context.Refresh(RefreshMode.StoreWins, refreshableObjects);

And I prefer the following:

var refreshableObjects = myDbContext.ChangeTracker.Entries().Select(c=>c.Entity).ToList();
context.Refresh(RefreshMode.StoreWins, refreshableObjects);