Re-use EF Core Expressions to avoid redundant queries

Re-use EF Core Expressions to avoid redundant queries

I often see snippets in EF Core code reviews such as the following:

dbContext.Users.Where( user => user.Id == id );

The query filter user => user.Id == id is contained directly in the Where - often not just in one place but sometimes in dozens of places. Here I ask myself: why is this not simply outsourced to a central place? It's so simple!

Especially when queries become more complex, with multiple and- or or-conditions, the duplications are a potential gateway for future bugs; when at one place of the query is updated, and other places are forgotten.

Static query classes

The query filter of Lambda queries are technically nothing more than Expressions. So why not just define the Expressions statically and allow reusability:

public static class UserEntityQueries
    public static Expression<Func<UserEntity, bool>> HasId(Guid id)
        => user => user.Id == id;

This static expression can now be used directly:

dbContext.Users.Where( UserEntityQueries.HasId(id) );

With very little effort, we not only have direct reusability and thus better maintainability, but have also created a very simple basis for unit testing through this construct.