Entity Framework Refresh context?

user2528557 picture user2528557 · Nov 28, 2013 · Viewed 161.4k times · Source

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!

Answer

RX_DID_RX picture RX_DID_RX · Nov 28, 2013

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