Easily use the Entity Framework cache

 
 
  • Gérald Barré

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

C#
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:

C#
context.GetEntitiesInCache<Person>();
context.GetEntitiesInCache<Person>(EntityState.Added);
context.GetEntitiesInCache<Person>(EntityState.Added | EntityState.Modified);

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub