1

I implemented an extension/helper called WhereIf of Type IQueryable, as you may have guessed by the name of it, it applies the filtering only if a pre-condition is met and is chained in EntityFramework query by code, but there were two problems with it and didn't work, and in another similar implementation, it worked fine. So why is that the first .Where didn't work but the second works just fine?

public static class WhereIfHelper
{
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool condition, Func<T, bool> expression)
        where T: class
    {
        return condition ? source.Where(expression) : source;
    }
}
  1. .Where() is of type IEnumarable which caused a runtime exception, so I used .AsQueryable() to solve it.
  2. When I called it threw: The source 'IQueryable' doesn't implement 'IAsyncEnumerable<Model>'. Only sources that implement 'IAsyncEnumerable' can be used for Entity Framework asynchronous operations. Which I don't know how to solve at this moment.

In the second code, I used a reference type instead of a generic and without a pre-condition.

public static class RepositoryIssueExtensions
{
    public static IQueryable<Game> FilterGames(this IQueryable<Game> games,
    DateTimeOffset initialDate,
    DateTimeOffset lastDate) => games.Where(i => i.CreatedAt >= initialDate && i.CreatedAt <= lastDate);
}

This time .Where is recognized as type IQueryable.

1 Answers1

4

Enumerable.Where accepts Func<> predicates while Queryable.Where requires symmetrical Expression<Func<>>'s, since IQueryable<T> implements IEnumerable<T> the only suitable overloads in the provided code are for IEnumerable. Change the method to accept Expression<Func<T, bool>> (you even have right parameter name):

public static class WhereIfHelper
{
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> source,
        bool condition, 
        Expression<Func<T, bool>> expression)
        where T: class
    {
        return condition ? source.Where(expression) : source;
    }
}

P.S.

Expression trees are used by queryable providers to analyze passed method and turn them into something else (like SQL in case of ORMs). Read more:

  1. What is the difference between IQueryable and IEnumerable?
  2. Expression trees
Guru Stron
  • 102,774
  • 10
  • 95
  • 132