Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104721

ObjectContext.Refresh()?

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.

Upvotes: 15

Views: 29516

Answers (4)

Christian Rodriguez
Christian Rodriguez

Reputation: 964

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/

Upvotes: 11

GBrian
GBrian

Reputation: 1

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.

Upvotes: 0

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104721

The following usually works:

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

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

Upvotes: 16

Daniel Elliott
Daniel Elliott

Reputation: 22857

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

Upvotes: 0

Related Questions