Easily use the Entity Framework cache

  • .NET

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);
Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal

Leave a reply