C#C
C#3y ago
Maskoe

❔ EF Core optional where extension method

I have a lot of optional parameters for queries. Filter by this, filter by that etc.
I can do it like this context.table.Where(x => projectId == null || x.ProjectId == projectId) (This actually doesnt even add a WHERE TRUE to the generated SQL Query Ok)
I would like to avoid the null check or part every time and write something like .OptionalWhere(x => x.ProjectId, projectId) but I cant find the correct syntax for the extension method.

Im trying stuff similiar to this
public static IQueryable<T> OptionalWhere<T, T2>(this IQueryable<T> source, Expression<Func<T, T2>> selector, T2 value)
    {
        if (value == null)
            return source;

        return source.Where(x => selector.Compile()(x).Equals(value));
    }


Func cant be translated. Expression cant be translated if I compile it. I guess because it turns into a func..

public static IQueryable<TSource> WhereNotNull<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
    {
        // somehow look into the predicate whether its an equals clause and check if the "right side" is null and return source back
        return source.Where(predicate);
    }
Was this page helpful?