Debugging database queries in Entity Framework Core can sometimes feel like searching for a needle in a haystack. When your application generates dozens or hundreds of SQL queries, identifying which LINQ query produced which SQL statement becomes a real challenge.
Fortunately, I discovered an elegant solution that EF Core provides: Query Tags.
Query Tags
Query Tags allow you to add custom comments to the SQL queries generated by your LINQ expressions. These comments appear directly in the generated SQL, making it incredibly easy to trace back from a SQL query to the specific code that created it.
To use this feature you need to apply the TagWith
method to your on any IQueryable
and pass a descriptive comment:
This generates SQL that looks like this:
Instead of trying to reverse-engineer which code generated a particular SQL query, you can immediately see the purpose and origin of each query in your database logs or profiler.
Advanced techniques
Chaining multiple tags
You can chain multiple TagWith
calls to add additional context:
This produces:
Remark: While the performance impact of TagWith
is minimal, avoid excessively long tags or complex string interpolation in hot paths.
Dynamic tags with context
You can create dynamic tags that include runtime information:
Remark: I like to use this to pass the OpenTelemetry correlation id as you can see in the example above. This helps to give end-to-end traceability.