【问题标题】:EFCore Lazy Loading with multiple where statements带有多个 where 语句的 EFCore 延迟加载
【发布时间】:2020-02-14 09:38:17
【问题描述】:

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

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

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

IQueryable&lt;Entity&gt; query = context.Entity;

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

 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。

我该如何解决这个错误?

非常感谢, 问候

【问题讨论】:

    标签: c# function entity-framework-core lazy-loading


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2012-01-28
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多