public static void ReloadEntity<TEntity>(
this DbContext context,
TEntity entity)
where TEntity : class
{
context.Entry(entity).Reload();
}
若要重新加载集合导航属性,可以使用
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();
}
如果您想使用 DbContextApi 重新加载特定的实体,RX _ did _ RX 已经给出了答案。
如果要重新加载/刷新所有已加载的实体:
If you are using Entity Framework 4.1+ (EF5, or EF 6 probably), DbContext API:
public void RefreshAll()
{
var entitiesList = ctx.ChangeTracker.Entries().ToList();
foreach (var entity in entitiesList)
{
entity.Reload();
}
}
如果使用 entityFramework4(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);
}
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
}