Writing an extension method for Entity Framework

别说谁变了你拦得住时间么 提交于 2021-02-08 10:13:11

问题


I would like to have an extension method called FirstOrDefaultCache()

which would check dbContext.EntityName.Local.FirstOrDefault(condition), and only if that is null, check dbContext.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!