Why does Entity Framework 6.x not cache results?

What @emcas88 is trying to say is that EF will only check the cache when you use the .Find method on DbSet.

Using .Single, .First, .Where, etc will not cache the results unless you are using second-level caching.


Sometimes I use my extension method:

using System.Linq;
using System.Linq.Expressions;

namespace System.Data.Entity
{
    public static class DbSetExtensions
    {
        public static TEntity FirstOrDefaultCache<TEntity>(this DbSet<TEntity> queryable, Expression<Func<TEntity, bool>> condition) 
            where TEntity : class
        {
            return queryable
                .Local.FirstOrDefault(condition.Compile()) // find in local cache
                   ?? queryable.FirstOrDefault(condition); // if local cache returns null check the db
        }
    }
}

Usage:

db.Invoices.FirstOrDefaultCache(x => x.CustomerName == "Some name");

You can replace FirstOrDefault with SingleOrDetfault also.


This is because the implementation of the extensor methods, use the Find method of the context

contextName.YourTableName.Find()

to verify first the cache. Hope it helps.