简体   繁体   English

实体框架 SelectMany 忽略 Where 子句

[英]Entity Framework SelectMany ignoring Where clause

I have an entity hierarchy such as: parent => child => grandchildren .我有一个实体层次结构,例如: parent => child => grandchildren

I have the parent entity loaded, now I need to do a group-by select of the grandchildren with a where-clause on the grand-children.我已经加载了parent实体,现在我需要对孙子进行分组选择,并在孙子上使用 where 子句。

The query I'm trying is essentially:我正在尝试的查询本质上是:

parent.Children
    .SelectMany(c => c.GrandChildren.Where(g=>g.BooleanField)) // try here
    .Where(g => g.BooleanField) // and try here
    .GroupBy(g => new { Name = g.FullName })
    .Select(m => new
    {
        m.Key.Name,
        Amount = m.Sum(o => o.DecimalField)
    })
    .OrderBy(m => m.Name);

The BooleanField filter is not being applied, though - I can see this from a SQL trace.虽然没有应用BooleanField过滤器 - 我可以从 SQL 跟踪中看到这一点。 I have it in two places, why is it not filtering?我有两个地方,为什么不过滤?

Edit编辑

The actual entities are projects, milestones and times.实际实体是项目、里程碑和时间。 Here is a screenshot of the entity framework code at the top, and the outputted TSQL beneath in the Output window.这是顶部实体框架代码的屏幕截图,下方是输出窗口中输出的 TSQL。 You can clearly see I have both WHERE clauses in place but the TSQL doesn't include the IsBillable field at all.您可以清楚地看到我有两个WHERE子句,但 TSQL 根本不包含 IsBillable 字段。

在此处输入图片说明

If project is some entity instance, and you're using lazy loading, then SQL from output is OK, because filtering and grouping is being performed at client side.如果project是某个实体实例,并且您使用的是延迟加载,那么输出中的 SQL 是可以的,因为过滤和分组是在客户端执行的。 EF can't filter child entities in this case using SQL query.在这种情况下,EF 无法使用 SQL 查询过滤子实体。

The only query against database here is a query, that loads Times of the particular Milestone :针对数据库这里唯一的查询是一个查询,加载Times特定的Milestone

project
    .Milestones // this is loaded already for some reason
    .SelectMany(m => m.Times /* this causes lazy loading and SQL in output */ 
        .Where(...) // from here everything is being executed in memory)
    .Where(...)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM