2

I am using Entity framework 4 and I have the following piece of code:

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
        ....
    }
}

I don't understand why the resulting SELECT statmenet at line query.Any() does not have any WHERE clause. Neither filter from wherePredicate nor x.SpecialNeeds == 0 is applied.

Any idea?

UPDATE 1: The problem seems to be the wherePredicate, which is of type Func not Expression. I will try to use Expression.

4

1 回答 1

4

尝试将GetSuccessRate方法声明更改为

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

原因是里面有两个Where扩展方法:Enumerable.Where并且Queryable.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<TSource, bool>另一个Expression<Func<TSource, bool>>

在您更改声明后,.AsQueryable()调用将不会有任何区别。

于 2013-05-17T09:19:01.303 回答