如何在没有if语句(SUM / AVG)的情况下实现以下查询?

时间:2017-04-07 16:36:32

标签: entity-framework linq design-patterns group-by linq-expressions

public class DailyAggregator : Aggregator
{
    public override Dictionary<string, int?> Aggregate<T>(IQueryable<T> query, Expression<Func<T, DateTime>> groupByProperty, Expression<Func<T, double>> operationProperty = null)
    {
        if (operationProperty == null) // property of sum/avg (null = count)
            operationProperty = x => 1;

        if (_operationType.Equals(ReportAggregationOperation.Sum))
        {
            return query
                .GroupBy(g => new
                {
                    Day = TestableDbFunctions.TruncateTime(groupByProperty.Invoke(g))
                })
                .Select(x => new
                {
                    Key = x.Key.Day.ToString().Substring(0, 10),
                    Value = (int?) x.Sum(operationProperty.Compile()),
                })
                .ToDictionary(t => t.Key, t => t.Value);
        }
        else
        {
            return query
               .GroupBy(g => new
               {
                   Day = DbFunctions.TruncateTime(groupByProperty.Invoke(g))
               })
               .Select(
                x => new
                {
                    Key = x.Key.Day.ToString().Substring(0, 10),
                    Value = (int?) x.Average(operationProperty.Compile()),
                }).ToDictionary(t => t.Key, t => t.Value);
        }
    }
}

我正在使用IOC容器来创建像dailyaggreagtor / monthlyaggregator这样的实例...... 但我无法通过表达式构建此组,或者应用正确的设计模式来消除上述if语句。

编译和调用函数来自LinqKit扩展。 使用此聚合器的类正在查询数据库并收集呼叫中心报告的数据(例如,TotalCdrRecords报告,ReachedCdrRecords报告,CdrTalkTime报告,CdrCallAfterworkTime等,CDR是呼叫数据记录,实际上包含有关呼叫的所有信息) 。查询(T)的类型在报告类中指定,但基本上是一个IReportableEntity,但当然,operationProperty它可以是数据库实体的任何属性,我们可以执行count / sum / avg操作,groupByProperty是始终是DateTime列。

它生成以下sql查询:

SELECT 
1 AS [C1], 
SUBSTRING(CASE WHEN ([GroupBy1].[K1] IS NULL) THEN N'' ELSE  CAST( [GroupBy1].[K1] AS nvarchar(max)) END, 0 + 1, 10) AS [C2], 
 CAST( [GroupBy1].[A1] AS int) AS [C3]
FROM ( SELECT 
    [Filter1].[K1] AS [K1], 
    SUM([Filter1].[A1]) AS [A1]
    FROM ( SELECT 
        convert (datetime2, convert(varchar(255), [Extent1].[CreatedOn], 102) ,  102) AS [K1], 
        cast(1 as float(53)) AS [A1]
        FROM [dbo].[VCCCdr] AS [Extent1]
        WHERE ([Extent1].[CreatedOn] >= @p__linq__0) AND ([Extent1].[CreatedOn] <= @p__linq__1) AND ([Extent1].[CompanyId] = @p__linq__2)
    )  AS [Filter1]
    GROUP BY [K1]
)  AS [GroupBy1]

1 个答案:

答案 0 :(得分:3)

由于您使用的是LINQKit,因此您可以提取一个表达式,以便在查询中调用Sum / Average部分和Invoke

例如:

var aggregateFunc = _operationType.Equals(ReportAggregationOperation.Sum) ?
        Linq.Expr((IEnumerable<double> source) => source.Sum()) :
        Linq.Expr((IEnumerable<double> source) => source.Average());

return query
    .GroupBy(g => new
    {
        Day = DbFunctions.TruncateTime(groupByProperty.Invoke(g))
    })
    .Select(x => new
    {
        Key = x.Key.Day.ToString().Substring(0, 10),
        Value = (int?)aggregateFunc.Invoke(x.Select(operationProperty.Compile())),
    })
    .ToDictionary(t => t.Key, t => t.Value);