Entity Framework Refresh context?

C#asp.netEntity Framework

C# Problem Overview


How could I refresh my context? I have entities based on views from my Database and when I made an update over one table Entity that has navigation properties to views, the entity is update but the view don't refresh accord the new updates...just want to get again from the Db the data. Thanks!

C# Solutions


Solution 1 - C#

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();
    }

Reference: https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry.reload(v=vs.113).aspx#M:System.Data.Entity.Infrastructure.DbEntityEntry.Reload

Solution 2 - C#

yourContext.Entry(yourEntity).Reload();

Solution 3 - C#

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:

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

Solution 4 - C#

Use the Refresh method:

context.Refresh(RefreshMode.StoreWins, yourEntity);

or in alternative dispose your current context and create a new one.

Solution 5 - C#

context.Reload() was not working for me in MVC 4, EF 5 so I did this.

context.Entry(entity).State = EntityState.Detached;
entity = context.Find(entity.ID);

and its working fine.

Solution 6 - C#

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

Solution 7 - C#

Refreshing db context with Reload is not recommended way due to performance loses. It is good enough and the best practice to initialize a new instance of the dbcontext before each operation executed. It also provide you a refreshed up to date context for each operation.

using (YourContext ctx = new YourContext())
{
   //Your operations
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2528557View Question on Stackoverflow
Solution 1 - C#RX_DID_RXView Answer on Stackoverflow
Solution 2 - C#kravits88View Answer on Stackoverflow
Solution 3 - C#Christian RodriguezView Answer on Stackoverflow
Solution 4 - C#AlbertoView Answer on Stackoverflow
Solution 5 - C#Chaudhary Kaleem AhmadView Answer on Stackoverflow
Solution 6 - C#Mahbubur RahmanView Answer on Stackoverflow
Solution 7 - C#aogView Answer on Stackoverflow