Why does Entity Framework 6.x not cache results?

后端 未结 6 1264
生来不讨喜
生来不讨喜 2020-12-04 16:56

Perhaps I am misunderstanding the caching that DbContext and DbSet does but I was under the impression that there was some caching that would go on

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 17:13

    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(this DbSet queryable, Expression> 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.

提交回复
热议问题