In this lesson, you will learn how to embed correlation IDs directly into your generated SQL queries to make pinpointing performance bottlenecks in your database logs effortless.
The Challenge of Blind Queries
When you view your database’s "Slow Query" log, you are often met with standard SQL statements that look identical across your application. If your service performs the same SELECT operation in ten different places, identifying which specific piece of code triggered a slow query becomes a game of guesswork.
Introducing TagWith
Entity Framework Core provides a feature called TagWith that allows you to inject a comment string into the generated SQL. When EF Core translates your LINQ query into SQL, it appends your tag as a SQL comment.
Here is how you can use it to inject a correlation ID or a descriptive label:
var correlationId = Guid.NewGuid().ToString();
var orders = await _context.Orders
.TagWith($"CorrelationID:{correlationId}")
.Where(o => o.IsActive)
.ToListAsync();
When this executes, the database engine receives the following SQL (formatted for clarity):
-- CorrelationID:550e8400-e29b-41d4-a716-446655440000
SELECT [o].[Id], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[IsActive] = 1
Why This Matters for Profiling
Because the correlation ID is now part of the SQL text, your database monitoring tools (such as SQL Server Profiler, Query Store, or APM tools like Application Insights) will capture this string.
If you integrate this with your application’s logging pipeline—for example, by including the same correlationId in your ILogger output—you can search your database logs for the ID and immediately trace it back to the exact user request or background process that initiated it. This bridges the gap between your C# application layer and the raw database execution engine.
Key Takeaway: Use .TagWith() to inject identifiable markers into your SQL queries, allowing you to trace expensive database operations directly back to the specific code path that invoked them.