EntityFramework LINQ query count fails but query returns result. How to optimize LINQ query?

前端 未结 2 2011
余生分开走
余生分开走 2021-01-21 14:13

I have the below LINQ query that performs a self-left-outer-join. The querys looks a little complex but is simply doing a self join on itself(purpose if to join each record with

相关标签:
2条回答
  • 2021-01-21 14:50

    Not quite sure that's the problem, but at least let try to eliminate the potential effect of the so called Parameter Sniffing Problem by eliminating the dateStart / dateEnd parameters by manually building expression with constant values.

    First, a little helper method:

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    
    public static class QueryableUtils
    {
        public static IQueryable<T> WhereBetween<T>(this IQueryable<T> source, Expression<Func<T, DateTime>> dateSelector, DateTime? startDate, DateTime? endDate)
        {
            if (startDate == null && endDate == null) return source;
            var startCond = startDate != null ? Expression.GreaterThanOrEqual(dateSelector.Body, Expression.Constant(startDate.Value)) : null;
            var endCond = endDate != null ? Expression.LessThanOrEqual(dateSelector.Body, Expression.Constant(endDate.Value)) : null;
            var predicate = Expression.Lambda<Func<T, bool>>(
                startCond == null ? endCond : endCond == null ? startCond : Expression.AndAlso(startCond, endCond),
                dateSelector.Parameters[0]);
            return source.Where(predicate);
        }
    }
    

    Then try the following and see if it helps:

    //if (dateStart.HasValue)
    //    query = query.Where(e => e.outer.ValueDate >= dateStart.Value);
    //if (dateEnd.HasValue)
    //    query = query.Where(e => e.outer.ValueDate <= dateEnd.Value);
    query = query.WhereBetween(e => e.outer.ValueDate, dateStart, dateEnd);
    
    0 讨论(0)
  • 2021-01-21 14:58

    You can simply use AsParallel() to enable multithreading execution of the linq query. You should then check your tables' indexes to improve performances.

    0 讨论(0)
提交回复
热议问题