Ada*_*lin 39 c# caching entity-framework entity-framework-6
也许我误解的缓存是DbContext
和DbSet
做,但我的印象是,有一些高速缓存,将继续下去.当我运行以下代码时,我看到了我不会期望的行为:
var ctx = CreateAContext();
var sampleEntityId = ctx.SampleEntities.Select(i => i.Id)
.Single(i => i == 3); //Calls DB as expected
var cachedEntityId = ctx.SampleEntities.Select(i => i.Id)
.Single(i => i == 3); //Calls DB unexpectedly
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?我认为你得到的部分原因DbSet
是它首先检查本地缓存,以便在查询数据库之前查看该对象是否存在.我在这里缺少某种配置选项吗?
dan*_*wig 42
什么@ emcas88想说的是,当你使用EF只会检查缓存.Find
的方法DbSet
.
使用.Single
,.First
,.Where
等不会,除非你使用的二级缓存缓存的结果.
emc*_*s88 29
这是因为执行了extensor方法,使用了上下文的Find方法
contextName.YourTableName.Find()
Run Code Online (Sandbox Code Playgroud)
首先验证缓存.希望能帮助到你.
cry*_*yss 23
有时我使用我的扩展方法:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
db.Invoices.FirstOrDefaultCache(x => x.CustomerName == "Some name");
Run Code Online (Sandbox Code Playgroud)
您也可以使用SingleOrDetfault替换FirstOrDefault.
EF6不会执行缓存ootb的结果.要缓存结果,您需要使用二级缓存.在CodePlex上看到这个有前景的项目:
请记住,如果数据库中的数据发生更改,您将无法立即了解它.有时这取决于项目很重要.;)