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

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Mon, 19 Mar 2012 11:29:41 GMT Indexed on 2012/03/19 18:05 UTC
Read the original article Hit count: 435

Filed under:
|
|
|
|

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:

   1: public static class DbContextExtensions
   2: {
   3:     public static IQueryable<T> LocalOrDatabase<T>(this DbContext context, Expression<Func<T, Boolean>> expression) where T : class
   4:     {
   5:         IEnumerable<T> localResults = context.Set<T>().Local.Where(expression.Compile());
   6:  
   7:         if (localResults.Any() == true)
   8:         {
   9:             return (localResults.AsQueryable());
  10:         }
  11:  
  12:         IQueryable<T> databaseResults = context.Set<T>().Where(expression);
  13:  
  14:         return (databaseResults);
  15:     }
  16: }

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about .NET 4