[转]Entity Framework Refresh context?

本文转自:http://stackoverflow.com/questions/20270599/entity-framework-refresh-context

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




Use the Refresh method:

context.Refresh(RefreshMode.StoreWins, yourEntity);

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

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





http://stackoverflow.com/questions/15828811/entity-framework-caching-issue

 

If you know that changes happened outside of EF and want to refresh your ctxt for a specific entity, you can call ObjectContext.Refresh

datamodel.Refresh(RefreshMode.StoreWins, orders);

If this seems like it will be a common occurance, you should disable object caching in your queries:

SchoolBriefcaseEntities datamodel = new SchoolBriefcaseEntities();
datamodel.tblCities.MergeOption = MergeOption.NoTracking; 

or for to turn off object level caching for specific Entity,

Context.Set<Compliances>().AsNoTracking();
原文地址:https://www.cnblogs.com/freeliver54/p/6639678.html