Entity Framework Code First: Get Entities From Local Cache or the Database
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: }