
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

Jul 03, 2023 - 5 min read
Easy InMemory Unit Tests with EFCore and Sqlite
Unit testing is a type of software testing that is performed on the smallest unit of a software application, called a “unit”. A …

Jun 20, 2023 - 3 min read
Better Code with custom Strong-Id Types
In many software architectures the problem exists that there are methods, which are specified a multiplicity of type-same parameters, whose …

Jun 10, 2023 - 3 min read
Value Converters in EFCore
In the field of software development, data transformation plays a key role in ensuring that information flows seamlessly between different …
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.
