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

Published Tue, Apr 7 2009 16:11 by Matthieu MEZIL

Comments

# re: EF: Working with the context cache

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. :-)

Tuesday, April 07, 2009 8:04 PM by Julie Lerman

Leave a Comment

(required) 
(required) 
(optional)
(required)