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

This entry was posted in 7671, 7674. Bookmark the permalink.

One Response to EF: Working with the context cache

  1. Julie Lerman says:

    Hey Matthieu
    I feel the same way about typing those over and over. What I did instead was just create overrides so that I can continue to call GetObjectStateEntries.

    One override takes 0 arguments – that returns all states.

    Another takes the entity state enum arguments plus a generic type, which like yours, queries for entries whose entity is of the requested type and the requested entity state(s).

    Another takes NO entity state enum arguments and the generic type. That gives back all entries of the type, regardless of the state.

    I’ve got them in my book, but I should probably share them on the blog as well. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *