EF: Working with the context cache
When we want to work with ObjectContext cache, we have to use the ObjectStateManager with its boring syntax.
products = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(ose => ose.Entity).OfType<Product>();
My idea is to make it into an extension method:
public static class ContextCacheExtension
{
public static IEnumerable<T> GetEntitiesInCache<T>(this ObjectContext context)
{
return context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(ose => ose.Entity).OfType<T>();
}
}
Now, I can have a "nicer" code:
products = context.GetEntitiesInCache<Product>();