【问题标题】:How can I achieve to implement the below query without the if statement (SUM/AVG)?如何在没有 if 语句(SUM/AVG)的情况下实现以下查询?
【发布时间】:2017-09-03 03:13:01
【问题描述】:
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 操作的 DB 实体的任何属性,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]

【问题讨论】:

  • 出于好奇,它是否完全按照它的编写方式工作?但建设性地,为了得到有意义的答案,有太多的缺失信息——querygroupByoperationProperty 变量的类型、InvokeCompile(LINQKit?)的使用等。跨度>
  • 是的,除了 tostring 部分之外它可以工作,但我编辑了帖子。是的,编译和调用是 LinqKit 的一部分。

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


【解决方案1】:

由于您使用的是 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);

【讨论】:

  • 像魅力一样工作 :) 非常感谢!我希望这对其他人有用,因为我没有发现关于通过表达式提取组的一部分的类似问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2018-10-25
  • 2018-06-27
  • 1970-01-01
  • 2012-01-28
  • 2019-03-06
相关资源
最近更新 更多