15

How to update ALL the dirty entities from the data store, and reset their changed values to the original store value?

The method ObjectContext.Refresh requires as a parameter the entities to be refreshed.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632

4 Answers4

16

The following usually works:

Context.Refresh(RefreshMode.StoreWins, _
    Context.ObjectStateManager.GetObjectStateEntries())

It sometimes causes problems with EntityRelations. look at my comment for further details.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
11

You can use this code:

public void RefreshAll()
{
     // Get all objects in statemanager with entityKey 
     // (context.Refresh will throw an exception otherwise) 
     var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(
                                                 EntityState.Deleted 
                                               | EntityState.Modified 
                                               | EntityState.Unchanged)
                                      where entry.EntityKey != null
                                      select entry.Entity);

     context.Refresh(RefreshMode.StoreWins, refreshableObjects);
}

I wrote a post on how to RefreshAll() and refresh the context in some other ways:

http://christianarg.wordpress.com/2013/06/13/entityframework-refreshall-loaded-entities-from-database/

Christian Rodriguez
  • 944
  • 1
  • 9
  • 20
  • This will throw an exception if you have added items. Add this before to fix: `var addedEntries = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added).ToList(); addedEntries.ForEach(entry => entry.Delete());` – AncientSyntax Mar 06 '15 at 14:43
  • @AncientSyntax You are right about the exception. Actually if you think about is it doesn't make sense to try to refresh a just added entity. I've edited the response removing the EntityState.Added from the code. In your proposed solution you are actually deleting the just added entity, so nothing will be added. – Christian Rodriguez Jul 20 '15 at 11:33
  • Is this related to SQL Version, so it works when running on a 12.0 SQL server but 11.0 ? – jcubero Mar 30 '16 at 19:07
0

If you want to reset ALL the changes, you could set the ObjectContext to null and re-instantiate it.

I believe this will achieve what you want.

Kindness,

Dan

Daniel Elliott
  • 22,647
  • 10
  • 64
  • 82
0

We use this:

return Context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted
System.Data.EntityState.Modified).All(ose 
  => {
    if(ose.Entity != null)
      Context.Refresh(RefreshMode.StoreWins, ose.Entity);
      return true;
    });

Where "Context" is the context to refresh. We filter by change state and entities to avoid new entities and relations.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
GBrian
  • 1