
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

Jan 13, 2025 - 5 min read
Advanced Usage of MSSQL Indexed Views in EF Core
In the world of Microsoft SQL Server , views are a powerful tool for simplifying complex data queries. Simple views offer no real …

Jan 03, 2025 - 2 min read
Increase Command Timeout for EF Core Migration Bundles
EF Core Migration Bundles are standalone executable files that contain one or more Entity Framework Core migrations and can be applied …

Nov 19, 2023 - 2 min read
New Data Annotation attributes with .NET 8
With .NET 8, the System.ComponentModel.DataAnnotations Namespace has been revised and some new attributes have been added that have been …
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.
