© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
7 replies
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)
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)
.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));
    }
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);
    }
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);
    }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

EF Core - Generic repository update method
C#CC# / help
4y ago
EF Core Where on multiple fields
C#CC# / help
2y ago
EF Core
C#CC# / help
2y ago
❔ Mocking EF Core extensions methods.
C#CC# / help
3y ago