Easily use the Entity Framework cache

In the extension methods series, here are two more. These allow you to use the Entity Framework cache more easily.

public static IEnumerable<T> GetEntitiesInCache<T>(this ObjectContext context)
{
    return GetEntitiesInCache<T>(context, EntityState.Added | EntityState.Modified | EntityState.Unchanged);
}

public static IEnumerable<T> GetEntitiesInCache<T>(this ObjectContext context, EntityState state)
{
    Contract.Requires(context != null);
    return context.ObjectStateManager.GetObjectStateEntries(state).Select(objectStateEntry => objectStateEntry.Entity).OfType<T>();
}

Some examples of use:

context.GetEntitiesInCache<Person>();
context.GetEntitiesInCache<Person>(EntityState.Added);
context.GetEntitiesInCache<Person>(EntityState.Added | EntityState.Modified);
Enjoy this blog? Buy Me A Coffee Donate with PayPal

Leave a reply