"进样" IQueryable中的WHERE子句在执行GROUP BY之前

时间:2016-10-03 08:28:55

标签: linq

我有两个表:FooBar参与1:M关系,也就是说,每个Foo都有许多相关的Bar个实例。

我有这样的查询:

IQueryable< IGrouping< Foo, Bar > > GetGroups() {

    return this.dbContext
        .Bar
        .Include( bar => bar.Foo )
        .GroupBy( bar => bar.Foo );
}

GetGroups的使用者可以应用适用于每个组的谓词,例如过滤Foo的属性(这是组密钥):

IQueryable< IGrouping< Foo, Bar > > query = GetGroups();

query = query.Where( grp => grp.Key.SomeFooProperty == "abc" );
query = query.OrderByDescending( grp => grp.Key.FooCreatedDate );

但是,如果GetGroups的使用者想要将谓词应用于返回的Bar行,该怎么办?

直接的解决方案是将其作为GetGroups

的参数提供
    IQueryable< IGrouping< Foo, Bar > > GetGroups( Func<Bar,Boolean> barPredicate ) {

    return this.dbContext
        .Bar
        .Include( bar => bar.Foo )
        .Where( barPredicate )
        .GroupBy( bar => bar.Foo );
}

然而,在我的情况下,这不是一个选项。

另一个选择是执行SelectMany然后手动重新组合,但这看起来很难看,我确定会产生次优的SQL:

IQueryable<Bar> barsQuery = query.SelectMany( grp => grp );
barsQuery = barsQuery.Where( barPredicate );
query = barsQuery.GroupBy( bar => bar.Foo );

有没有办法检查IQueryable和&#34;注入&#34;我的Where条款介于Include GroupBy语句之间?

0 个答案:

没有答案
相关问题