
I often see snippets in EF Core code reviews such as the following:
1dbContext.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:
1public static class UserEntityQueries
2{
3 public static Expression<Func<UserEntity, bool>> HasId(Guid id)
4 => user => user.Id == id;
5}
This static expression can now be used directly:
1dbContext.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.
Related articles

Mar 10, 2026 · 15 min read
.NET NuGet Trusted Publishing with GitHub Actions
Publishing NuGet packages has traditionally required one uncomfortable compromise: a long-lived API key had to exist somewhere in the …

Mar 09, 2026 · 7 min read
C# 15 Unions: Unions are finally in .NET
After many years of workarounds, design discussions and library-level substitutes, unions are finally becoming a first-class part of C#. The …

Mar 02, 2026 · 19 min read
Unio: High-Performance Discriminated Unions for C#
C# is a powerful language, but there is one road it has not yet fully paved: native discriminated union types. Developers have been working …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

Comments