Monthly Archives: June 2013

EntityFramework RefreshAll loaded entities from Database

This samples will talk about Entity Framework 4 (ObjectContext). I’ll show in a next post how to get this done with EF5 DbContext. It should be much easier.

Update: here it is, finally:

Update2: based on feedback on stackoverflow I’ve found a bug in the code. I was actually trying to refresh a just added entity, which will result in an exception. So I’ve removed EntityState.Added from the GetObjectStateEntries parameters.

With the default behaviour, once we get an entity from the Database, if it is changed in background, and even if you query the entity again, you will see the old values.

The easy way to solve this is two use very short lived context, and “reload” the entity in another context. If that is not posible (ex: you are using the context in a PerRequest basis, or Ioc Container Controlled) you have some options:

Refresh all loaded entities from Database

This code is simple and it can be very helpful, but you must be aware that it will reload ABSOLUTELLY ALL THE OBJECTS THAT YOU HAVE ALREADY QUERIED. If you queried many entites, it will have a negative performance impact

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.Modified
                                               | EntityState.Unchanged)
                                      where entry.EntityKey != null
                                      select entry.Entity);

     context.Refresh(RefreshMode.StoreWins, refreshableObjects);


  • Very easy to use, once you have the code above :)


  • Potentially, it could execute A LOT of queries in order to refresh a context that “used” many queries

Refresh specific entities

Let’s assume we have a Blog application for the example.

// First we need to Add the objects to our refresh list
var objectsToRefresh = new List<System.Object>();

foreach (var comment in blogPost.Comments)
 // etc
// Here it ended your application custom Code. Now you have to:

// Clean nulls and repeateds (context.Refresh will throw an exception otherwise)
var noNullsAndRepeateds = objectsToRefresh.Where(o => o != null).Distinct().ToList();

// Get only the entities that are being tracked by ObjectStateManager and have entityKey
// (context.Refresh will throw an exception otherwise)
var finalList = (from e in entityContext.ObjectStateManager.GetObjectStateEntries(
                                               | EntityState.Modified
                                               | EntityState.Unchanged)		

		where e.EntityKey != null &&
		select e.Entity).ToList();

entityContext.Refresh(RefreshMode.StoreWins, finalList);


  • Granular queries
  • Easy to use, once you have the code above :)


  • The problem is if you have an aggregate or object complex graph.You need to “craft” code to refresh each aggregate.
  • You have to manually “inform” which objects to refresh

Use MergeOptions
There are many resources on the web on how to do this

var query = context.BlogPosts;
query.MergeOption = MergeOption.OverwriteChanges;
var blogPost = query.SingleOrDefault(b=> b.Id == 1);


  • A good and recommended aproach.
  • Granular queries


  • Again, if you have an aggregate or object complex graph. You’ve probably had query it using multiple queries (ex: because when tunning and profiling you got better results). If this is the case you would need to specify the MergeOption for each query. That could be hard work
  • Manually refresh only affected objects
  • The way of specifying it in EF4 is a bit counter-intuitive