按查询分组未按预期执行

时间:2018-08-07 09:38:06

标签: oracle linq .net-core entity-framework-core dynamicquery

我对这样的TheEntity类型有这样的查询:

        var source = await _repository.Queryable.AsNoTracking()
            .Where(Condition1())
            .Where(Condition2(params))
            .GroupBy(GroupByFunction)
            .Select(SelectFunction)
            .OrderBy(o => o.Field1)
            .ToAsyncEnumerable().ToList();

此查询选择满足条件的所有记录:Condition1,Condition2,但未按我的预期将它们分组。

SelectFunction和GroupByFunction如下所示:

    private readonly Expression<Func<IGrouping<TheEntityGroupByData, TheEntity>, TheEntitySelectData>> SelectFunction =
        e => new TheEntitySelectData()
        {
            Field1 = e.Key.Field1,
            Field2 = e.Key.Field2,
            ...
            FieldN = e.Key.FieldN,
            Field(N+1) = e.Sum(x=>x.Field(N+1)),
            ...
            FieldK = e.Sum(x=>x.FieldK),
        };

    private readonly Expression<Func<TheEntity, TheEntityGroupByData>> GroupByFunction =
        e => new TheEntityByData()
        {
            Field1 = e.Field1,
            Field2 = e.Field2,
            ...
            FieldN = e.Key.FieldN,
        };

TheEntityGroupByData,TheEntitySelectData是辅助DTO / PO_Os类型。 我打算在数据库而不是服务器上进行分组,但是这种行为即使在服务器内存中也行不通。

我使用.Net Core 2.0.5和EntityFrameworkCore 2.0.2。

我的问题是这种方法的问题在哪里?


edit-我的意思是查询无法按预期工作是因为:如果我在db中有两个相同的记录(通过分组键相同)满足Condition1和Condition2,查询将返回2,而不是一个记录。

>

过滤条件如下:

private static Expression<Func<TheEntity, bool>> Condition1()
{
    return (e) => e.Field1 == SOME_CONSTANT;
}

private static Expression<Func<TheEntity, bool>> Condition2(RequestParam param)
{
    Expression<Func<TheEntity, bool>> whereSth;
    if (param.some.HasValue)
        whereSth = (e) => e.Field2 <= param.some.Value;
    else
        whereSth = (e) => true;
    return whereSth;
}

0 个答案:

没有答案