Entity Framework Code First: Get Entities From Local Cache or the Database

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Entity Framework Code First makes it very easy to access local (first level) cache: you just access the DbSet<T>.Local property. This way, no query is sent to the database, only performed in already loaded entities.

If you want to first search local cache, then the database, if no entries are found, you can use this extension method:

public static class DbContextExtensions
{
   public static IQueryable LocalOrDatabase(this DbContext context, Expression<Func<T, Boolean>> expression) where T : class
  {
   IEnumerable localResults = context.Set().Local.Where(expression.Compile());
   if (localResults.Any() == true)
   {
       return (localResults.AsQueryable());
   }
   IQueryable databaseResults = context.Set().Where(expression);
   return (databaseResults);
  }
}<br />

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.