实体框架,通过阻止左外连接的顺序

时间:2018-04-27 11:53:01

标签: c# entity-framework linq

我有一个以下查询,这导致我在SQL服务器中出现性能问题。

ctx.Articles
    .Where(m => m.Active)
    .Where(m => m.PublishDate <= DateTime.Now)
    .Where(m => m.Sponsored == false)
    .WhereIf(request.ExcludeFirstNews, m => m.PositionForCategory != 1)
    .WhereIf(category != null, m => m.RootCategoryId == category.RootCategoryId)
    .WhereIf(request.TimeRange != 0 && request.TimeRange == TimeRange.today, m => m.PublishDate.Value >= today)
    .WhereIf(request.TimeRange != 0 && request.TimeRange == TimeRange.yesterday, m => m.PublishDate.Value >= yesterday)
    .WhereIf(request.TimeRange != 0 && request.TimeRange == TimeRange.week, m => m.PublishDate.Value >= week &&
                                                       m.PublishDate.Value <= DateTime.Now)
    .WhereIf(request.TimeRange != 0 && request.TimeRange == TimeRange.month, m => m.PublishDate.Value >= month &&
                                                        m.PublishDate.Value <= DateTime.Now)
    .OrderByDescending(m => m.ArticleViewCountSum.ViewCountSum)

有没有办法让lambb表达式的语法部分使实体框架使用内连接而不是左外连接? 我在profiler中检查了查询,并且它生成器离开了外连接,在这种情况下不是必需的,如果我在SQL中手动更改查询,运行速度会快得多。

编辑: 每个问题,在评论中,这是WhereIf的代码

public static IQueryable<T> WhereIf<T>(
            this IQueryable<T> source,
            bool condition,
            Expression<Func<T, bool>> predicate)
        {
            if (condition)
            {
                return source.Where(predicate);
            }

            return source;
        }

0 个答案:

没有答案