Entity Framework Refresh context? [closed]
The best way to refresh entities in your context is to dispose your context and create a new one.
If you really need to refresh some entity and you are using Code First approach with DbContext class, you can use
public static void ReloadEntity<TEntity>( this DbContext context, TEntity entity) where TEntity : class { context.Entry(entity).Reload(); }
To reload collection navigation properties, you can use
public static void ReloadNavigationProperty<TEntity, TElement>( this DbContext context, TEntity entity, Expression<Func<TEntity, ICollection<TElement>>> navigationProperty) where TEntity : class where TElement : class { context.Entry(entity).Collection<TElement>(navigationProperty).Query(); }
If you want to reload specific entities, with the DbContextApi, RX_DID_RX already gave you the answer.
If you want to reload / refresh all the entities you loaded:
If you are using Entity Framework 4.1+ (EF5, or EF 6 probably), DbContext API:
public void RefreshAll(){ foreach (var entity in ctx.ChangeTracker.Entries()) { entity.Reload(); }}
If you are using entityFramework 4 (ObjectContext API):
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);}
Best advice anyway is, try to use a "short lived context" and you'll avoid this kind of problems.
I wrote a couple of articles on the matter: