编写实体框架的扩展方法 [英] Writing an extension method for Entity Framework

查看:40
本文介绍了编写实体框架的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个名为 FirstOrDefaultCache()

这将检查 dbContext.EntityName.Local.FirstOrDefault(condition),并且仅当为空,请检查 dbContext.EntityName.FirstOrDefault(condition).

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
} 

但是,我不能在 .Include()之后使用它.

However, I cannot use this after a .Include().

dbContext.EntityName.FirstOrDefaultCache(某些条件); 有效,但是 dbContext.EntityName.Include(x => x.NavProperty).FirstOrDefaultCache(某些条件); 不起作用.

推荐答案

您需要使用 IQueryable< T> ,以便能够在 Include 或位置或其他任何位置.但是,由于未缓存查询结果,因此您将无法在扩展程序中使用 Local .

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.

您的选项是禁用某些包含的属性的延迟加载,以避免 Include

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.

您可以这样使用它:

var result = q.Take(10).FromCache()

在您的情况下,其外观可能类似于:

In your case it would probably look something like:

dbContext.EntityName.Include(x => x.NavProperty).FromCache().First(condition)

这篇关于编写实体框架的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆