问题
I would like to have an extension method called FirstOrDefaultCache()
which would check
dbContext.EntityName.Local.FirstOrDefault(condition)
, and only if that is null, checkdbContext.EntityName.FirstOrDefault(condition)
.
I got the following from another post, which works okay:
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
}
However, I cannot use this after a .Include()
.
dbContext.EntityName.FirstOrDefaultCache(some condition);
works, but dbContext.EntityName.Include(x => x.NavProperty).FirstOrDefaultCache(some condition);
does not work.
回答1:
You need to use IQueryable<T>
in order to be able to use your extension method after Include
or Where
or any other. But because query results are not cached, you will not be able to use Local
in your extension.
Your options are to disable lazy loading for certain included properties to avoid Include
or you could implement some kind of second level cache for your queries. For example this one, but I have not tried it and it is quite old.
you use it like this:
var result = q.Take(10).FromCache()
In your case it would probably look something like:
dbContext.EntityName.Include(x => x.NavProperty).FromCache().First(condition)
来源:https://stackoverflow.com/questions/36490302/writing-an-extension-method-for-entity-framework