【问题标题】:Why the AsQueryable following by Any leads to select without Where clasue?为什么 Any 后面的 AsQueryable 导致选择没有 Where 子句?
【发布时间】:2013-05-17 08:54:09
【问题描述】:

我正在使用实体框架 4,并且我有以下代码:

public decimal GetSchoolSuccessRate(EvaluationComparationFilter filter)
{
    return this.GetSuccessRate(x => x.TestCampaignId == filter.TestCampaignId &&
                      x.SubjectId == filter.SubjectId &&
                      x.SectionNo == 0, filter.CountSvp);
}


private decimal GetSuccessRate(Func<FinalResult_Base, bool> wherePredicate, bool countSvp)
{
    using (var db = new DataEntities())
    {
        IQueryable<FinalResult_Base> query = db
                  .FinalResult_Bases.Where(wherePredicate).AsQueryable();


        if (!countSvp)
            query = query.Where(x => x.SpecialNeeds == 0);


        query.Any();   //--HERE is created the SELECT with NO WHERE clause
        ....
    }
}

我不明白为什么在query.Any() 行生成的SELECT statmenet 没有任何WHERE 子句。来自wherePredicatex.SpecialNeeds == 0 的过滤器均未应用。

有什么想法吗?

更新 1: 问题似乎是wherePredicate,它的类型是 Func 而不是 Expression。我会尝试使用表达式。

【问题讨论】:

  • 这听起来很奇怪。你为什么还要使用AsQueryable?考虑到您使用的是 EF,我没想到您需要这样做...
  • @Jon 好吧,老实说我没有写代码,但我想它需要动态构建查询。例如添加x =&gt; x.SpecialNeeds == 0 condition。这不正确吗?
  • IMO db.FinalResult_Bases.Where(wherePredicate) 已经是 IQueryable 所以你不需要 .AsQueryable();
  • 您是否使用调试器单步执行它是 countSvp false
  • @Grumbler85 我尝试过 countSvp 的真假。没有效果。

标签: c# .net sql entity-framework lambda


【解决方案1】:

尝试将GetSuccessRate 方法声明更改为

private decimal GetSuccessRate(
    Expression<Func<FinalResult_Base, bool>> wherePredicate, bool countSvp)

原因是内部有两个Where扩展方法:Enumerable.WhereQueryable.Where,它们有不同的声明:

public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate)

public static IQueryable<TSource> Where<TSource>(
    this IQueryable<TSource> source, 
    Expression<Func<TSource, bool>> predicate)

所以一个收到Func&lt;TSource, bool&gt;,另一个收到Expression&lt;Func&lt;TSource, bool&gt;&gt;

更改声明后,.AsQueryable() 调用将没有任何区别。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
相关资源
最近更新 更多