Re-use EF Core Expressions to avoid redundant queries

BEN ABT
medialesson
Published in
2 min readJul 31, 2023

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.

Autor

Benjamin Abt

Ben is a passionate developer and software architect and especially focused on .NET, cloud and IoT. In his professional he works on high-scalable platforms for IoT and Industry 4.0 focused on the next generation of connected industry based on Azure and .NET. He runs the largest german-speaking C# forum myCSharp.de, is the founder of the Azure UserGroup Stuttgart, a co-organizer of the AzureSaturday, runs his blog, participates in open source projects, speaks at various conferences and user groups and also has a bit free time. He is a Microsoft MVP since 2015 for .NET and Azure.

Originally published at https://schwabencode.com on July 31, 2023.

--

--