如何使用EF Core在已翻译的SQL中获得COUNT DISTINCT

时间:2019-06-28 08:45:04

标签: c# ef-core-2.1

我想让EF核心将.Select(x=>x.property).Distinct().Count()转换为

SELECT COUNT(DISTINCT property)

让我们举个例子。假设我有一个数据库表,其中包含PersonID(long),VisitStart(datetime2)和VisitEnd(datetime2)。 如果我想获取特定人员访问的不同天数,则可以编写类似

的SQL
SELECT COUNT(DISTINCT CONVERT(date, VisitStart)) FROM myTable GROUP BY PersonID

但是使用EF核心和

MyTable
    .GroupBy(x=>x.PersonID)
    .Select(x=> new 
    {
        Count = x.Select(y=>y.VisitStart.Date).Distinct().Count()
    })
提供正确结果的

会转换为该SQL

SELECT [x].[PersonID], [x].[VisitStart], [x].[VisitEnd]
FROM [myTable] as [x]
ORDER BY [x].[PersonID]

在任何地方都没有GROUP BY且没有DISTINCT或COUNT,因此必须在内存中进行分组,这在处理可能具有从数据库中提取的数百万条记录的表时是不理想的。

所以任何人都知道如何获得EF核心来将.Select(...).Distinct().Count()转换为SELECT COUNT(DISTINCT ...)

2 个答案:

答案 0 :(得分:5)

EF(6和Core)历史上不支持此标准SQL构造。最可能的原因是缺少标准的LINQ方法以及将Select(expr).Distinct().Count()映射到它的技术困难。

好处是,EF Core可扩展,方法是用自定义派生的实现替换其许多内部服务,以覆盖所需的行为。不容易,需要很多管道代码,但是可行。

因此,想法是添加并使用像这样的简单自定义CountDistinct方法

public static int CountDistinct<T, TKey>(this IQueryable<T> source, Expression<Func<T, TKey>> keySelector)
    => source.Select(keySelector).Distinct().Count();

public static int CountDistinct<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
    => source.Select(keySelector).Distinct().Count();

,然后让EF Core以某种方式将它们转换为SQL。实际上,EF Core提供了一种定义(甚至自定义翻译)数据库标量函数的简单方法,但是不幸的是,它不能用于具有单独处理管道的聚合函数。因此,我们需要深入研究EF Core基础架构。

最后提供了EF Core 2.x管道的完整代码。不确定是否值得努力,因为EF Core 3.0将使用完整的重写查询流程管道。但这很有趣,而且我很确定可以为新的(希望更简单的)管道对其进行更新。

无论如何,您所需要做的就是将代码复制/粘贴到项目中的新代码文件中,并将以下内容添加到上下文中OnConfiguring覆盖

optionsBuilder.UseCustomExtensions();

这会将功能插入EF Core基础架构,然后像这样查询

var result = db.MyTable
    .GroupBy(x => x.PersonID, x => new { VisitStartDate = x.VisitStart.Date })
    .Select(g => new
    {
        Count = g.CountDistinct(x => x.VisitStartDate)
    }).ToList();

将幸运地翻译为所需的

SELECT COUNT(DISTINCT(CONVERT(date, [x].[VisitStart]))) AS [Count]
FROM [MyTable] AS [x]
GROUP BY [x].[PersonID]

请注意预先选择聚合方法所需的表达式。这是对所有汇总方法(不仅仅是我们的方法)的当前EF Core限制/要求。

最后,完成魔术的完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.ResultOperators;
using Remotion.Linq.Clauses.StreamedData;
using Remotion.Linq.Parsing.Structure.IntermediateModel;

namespace Microsoft.EntityFrameworkCore
{
    public static partial class CustomExtensions
    {
        public static int CountDistinct<T, TKey>(this IQueryable<T> source, Expression<Func<T, TKey>> keySelector)
            => source.Select(keySelector).Distinct().Count();

        public static int CountDistinct<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
            => source.Select(keySelector).Distinct().Count();

        public static DbContextOptionsBuilder UseCustomExtensions(this DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .ReplaceService<INodeTypeProviderFactory, CustomNodeTypeProviderFactory>()
                .ReplaceService<IRelationalResultOperatorHandler, CustomRelationalResultOperatorHandler>();
    }
}

namespace Remotion.Linq.Parsing.Structure.IntermediateModel
{
    public sealed class CountDistinctExpressionNode : ResultOperatorExpressionNodeBase
    {
        public CountDistinctExpressionNode(MethodCallExpressionParseInfo parseInfo, LambdaExpression optionalSelector)
            : base(parseInfo, null, optionalSelector) { }
        public static IEnumerable<MethodInfo> GetSupportedMethods()
            => typeof(CustomExtensions).GetTypeInfo().GetDeclaredMethods("CountDistinct");
        public override Expression Resolve(ParameterExpression inputParameter, Expression expressionToBeResolved, ClauseGenerationContext clauseGenerationContext)
            => throw CreateResolveNotSupportedException();
        protected override ResultOperatorBase CreateResultOperator(ClauseGenerationContext clauseGenerationContext)
            => new CountDistinctResultOperator();
    }
}

namespace Remotion.Linq.Clauses.ResultOperators
{
    public sealed class CountDistinctResultOperator : ValueFromSequenceResultOperatorBase
    {
        public override ResultOperatorBase Clone(CloneContext cloneContext) => new CountDistinctResultOperator();
        public override StreamedValue ExecuteInMemory<T>(StreamedSequence input) => throw new NotSupportedException();
        public override IStreamedDataInfo GetOutputDataInfo(IStreamedDataInfo inputInfo) => new StreamedScalarValueInfo(typeof(int));
        public override string ToString() => "CountDistinct()";
        public override void TransformExpressions(Func<Expression, Expression> transformation) { }
    }
}

namespace Microsoft.EntityFrameworkCore.Query.Internal
{
    public class CustomNodeTypeProviderFactory : DefaultMethodInfoBasedNodeTypeRegistryFactory
    {
        public CustomNodeTypeProviderFactory()
            => RegisterMethods(CountDistinctExpressionNode.GetSupportedMethods(), typeof(CountDistinctExpressionNode));
    }

    public class CustomRelationalResultOperatorHandler : RelationalResultOperatorHandler
    {
        private static readonly ISet<Type> AggregateResultOperators = (ISet<Type>)
            typeof(RequiresMaterializationExpressionVisitor).GetField("_aggregateResultOperators", BindingFlags.NonPublic | BindingFlags.Static)
            .GetValue(null);

        static CustomRelationalResultOperatorHandler()
            => AggregateResultOperators.Add(typeof(CountDistinctResultOperator));

        public CustomRelationalResultOperatorHandler(IModel model, ISqlTranslatingExpressionVisitorFactory sqlTranslatingExpressionVisitorFactory, ISelectExpressionFactory selectExpressionFactory, IResultOperatorHandler resultOperatorHandler)
            : base(model, sqlTranslatingExpressionVisitorFactory, selectExpressionFactory, resultOperatorHandler)
        { }

        public override Expression HandleResultOperator(EntityQueryModelVisitor entityQueryModelVisitor, ResultOperatorBase resultOperator, QueryModel queryModel)
            => resultOperator is CountDistinctResultOperator ?
                HandleCountDistinct(entityQueryModelVisitor, resultOperator, queryModel) :
                base.HandleResultOperator(entityQueryModelVisitor, resultOperator, queryModel);

        private Expression HandleCountDistinct(EntityQueryModelVisitor entityQueryModelVisitor, ResultOperatorBase resultOperator, QueryModel queryModel)
        {
            var queryModelVisitor = (RelationalQueryModelVisitor)entityQueryModelVisitor;
            var selectExpression = queryModelVisitor.TryGetQuery(queryModel.MainFromClause);
            var inputType = queryModel.SelectClause.Selector.Type;
            if (CanEvalOnServer(queryModelVisitor)
                && selectExpression != null
                && selectExpression.Projection.Count == 1)
            {
                PrepareSelectExpressionForAggregate(selectExpression, queryModel);
                var expression = selectExpression.Projection[0];
                var subExpression = new SqlFunctionExpression(
                    "DISTINCT", inputType, new[] { expression.UnwrapAliasExpression() });
                selectExpression.SetProjectionExpression(new SqlFunctionExpression(
                    "COUNT", typeof(int), new[] { subExpression }));
                return new ResultTransformingExpressionVisitor<int>(
                    queryModelVisitor.QueryCompilationContext, false)
                    .Visit(queryModelVisitor.Expression);
            }
            else
            {
                queryModelVisitor.RequiresClientResultOperator = true;
                var typeArgs = new[] { inputType };
                var distinctCall = Expression.Call(
                    typeof(Enumerable), "Distinct", typeArgs,
                    queryModelVisitor.Expression);
                return Expression.Call(
                    typeof(Enumerable), "Count", typeArgs,
                    distinctCall);
            }
        }

        private static bool CanEvalOnServer(RelationalQueryModelVisitor queryModelVisitor) =>
            !queryModelVisitor.RequiresClientEval && !queryModelVisitor.RequiresClientSelectMany &&
            !queryModelVisitor.RequiresClientJoin && !queryModelVisitor.RequiresClientFilter &&
            !queryModelVisitor.RequiresClientOrderBy && !queryModelVisitor.RequiresClientResultOperator &&
            !queryModelVisitor.RequiresStreamingGroupResultOperator;
    }
}

答案 1 :(得分:1)

我想分享一个想法,以解决计数无关的问题。

最终,另一种按功能在一组中进行计数的方法是通过嵌套按功能进行组(假设您可以汇总数据)。

这里是我使用的示例,似乎有效。

对于the亵肢体的致歉,我正在使用它使我的JSON保持尽可能小。

var myData = _context.ActivityItems
                        .GroupBy(a => new { ndt = EF.Property<DateTime>(a, "dt").Date, ntn = a.tn })
                        .Select(g => new
                        {
                            g.Key.ndt,
                            g.Key.ntn,
                            dpv = g.Sum(o => o.pv),
                            dlv = g.Sum(o => o.lv),
                            cnt = g.Count(),
                        })
                        .GroupBy(a => new { ntn = a.ntn })
                        .Select(g => new
                        {
                            g.Key.ntn,
                            sd = g.Min(o => o.ndt),
                            ld = g.Max(o => o.ndt),
                            pSum = g.Sum(o => o.dpv),
                            pMin = g.Min(o => o.dpv),
                            pMax = g.Max(o => o.dpv),
                            pAvg = g.Average(o => o.dpv),
                            lSum = g.Sum(o => o.dlv),
                            lMin = g.Min(o => o.dlv),
                            lMax = g.Max(o => o.dlv),
                            lAvg = g.Average(o => o.dlv),
                            n10s = g.Sum(o => o.cnt),
                            ndays = g.Count()
                        });