【问题标题】:Using ThenInclude with condition in Entity Framework在实体框架中使用带条件的 ThenInclude
【发布时间】:2020-01-26 07:55:42
【问题描述】:
return _companyRepository.GetAll().Where(company => company.Id == Id)
             .Include(company => company.offices.Where(o => o.IsActive))
             .ThenInclude(office => office.People.Where(p => p.IsFired))
             .ThenInclude(person => person.Children)
             .ToList(); 

如何使用 Entity Framework Core 让所有活跃办公室的所有被解雇人员?

我收到此错误:

Where 子句在 ThenInclude 或 Include 中无效

company.offices.Where(o => o.IsActive) 
office.People.Where(p => p.IsFired)

我知道我不能在Include 中使用Where。问题是如何使用Include 子句过滤数据?

【问题讨论】:

  • 不要将 Where 表达式放入 Include 中。

标签: c# entity-framework-core


【解决方案1】:

这是不可能的。

我建议四处寻找那里列出的任何第 3 方库,例如:

EntityFramework.Filters

Query IncludeFilter

How to filter “Include” entities in entity framework?

【讨论】:

    【解决方案2】:

    如果您在查询中使用您的数据,则无需使用任何IncludeInclude 只是一种禁用延迟加载的方法。 Include 控制导航属性是否填充数据。 Include 不是用来过滤任何东西的。

    您的查询还将返回公司(有人员)而不是人员。

      return _companyRepository.GetAll().Where(company => company.Id == Id)
             .SelectMany(company => company.offices)
             .Where(o => o.IsActive)
             .SelectMany(office => office.People)
             .Where(p => p.IsFired) 
             .Include(person => person.Children)
             .ToList(); 
    

    这将创建一个包含人员的列表,包括他们的孩子。 最后一个include 控件说,所有的孩子都加载了这个查询。如果你删除这个include,你仍然可以访问孩子,但它是按需加载或延迟加载。您不会注意到程序的功能有任何不同,但与您的 sql-server 的通信不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      相关资源
      最近更新 更多