使用多个 where 语句的 EFCore 延迟加载

EFCore Lazy Loading with multiple where statements

我已经使用代理配置了延迟加载的 DbContext:

services.AddDbContext<MyDbContext>(options =>
                options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("Connection"), sqlServerOptions => sqlServerOptions.CommandTimeout(90)), ServiceLifetime.Transient);

我使用 IQueryable 定义针对具有多个导航属性的实体的查询:

IQueryable<Entity> query = context.Entity;

之后,我使用多个 Func 在 where 子句中定义了一个过滤器:

 Func<Entity, int, bool> GetByParentId = (entity, id) => { return entity.ParentId == id; };
 Func<Entity, string, bool> FilterByName = (entity, textToSearch) => { return entity.Name.Equals(textToSearch, StringComparison.OrdinalIgnoreCase); };
 Func<Entity, string, bool> FilterByStatus = (entity, textToSearch) => { return entity.IdStatusNavigation.Description.ToLower().Contains(textToSearch); };

 Func<AssetGroup, int, string, bool> FilterEntities = (entity, idParam, textToSearch) => {
                return GetByParentId (entity, idParam)
                    && (FilterByName(entity, textToSearch) || FilterByStatus(entity, textToSearch));
            };

query = query.Where(entity=> FilterEntities(entity, idParam, lowerTextToSearch));

当我执行 for(var entity on query) 时,第一个带有导航 属性 的函数被执行(FilterByName)并且实体上的所有属性,包括导航属性,有值,我可以导航到相关实体。

但是当执行第二个函数时 (FilterByStatus) 我收到以下错误:

尝试在 'EntityProxy' 类型的分离实体上延迟加载导航 属性 'IdStatusNavigation'。分离的实体或使用 'AsNoTracking()'

加载的实体不支持延迟加载

我没有使用 AsNoTracking...如果我调试进程,我可以看到在第二个函数导航属性上抛出异常 System.InvalidOperation。

如何解决这个错误?

非常感谢, 此致

好像Functions类型不能翻译成SQL语言,所以这段代码是在查询结果在内存中时执行的。因此,在访问第一个导航 属性 后,所有导航属性似乎都已处理,以后无法访问。

所以我重写了代码,以便使用内存中的数据制作此过滤器(在执行 ToList() 之后)。