Using query tags with Entity Framework Core 2.2

Entity Framework 2.2 introduces query tags that make it easier to find specific queries from logs and output windows of Visual Studio. When running application on development box it’s possible to live without query tags. We can set breakpoints to see SQL generated from LINQ queries. But how to find queries from log files in multithreaded or multiuser scenarios?

Finding queries from logs without query tags

But what if site has multiple users at same time? The following code works but it’s problematic.

_logger.LogInformation("Front page: new photos");

model.NewPhotos = await _dataContext.Photos
                                .ProjectTo<PhotoListModel>()
                                .ToListAsync();

Don’t be surprised if you see in log something like this:

Front page: new photos
Front page: new photos
<Some SQL>
<Different SQL>
<Another SQL>
Front page: new photos
<Some more SQL>
<Some SQL>
<Some SQL>

Looking at log like this makes probably ask one question: how to match information message above with SQL query in log?

Applying query tags

Query tags make it easy to answer the question as query description is always with generated SQL query. Use query tags like the following example shows.

model.NewPhotos = await _dataContext.Photos.TagWith("New photos for frontpage")
                                .ProjectTo<PhotoListModel>()
                                .ToListAsync();

Using TagWith() extension method you can be sure that query description is always logged with query. You can see query tags in action on the following screenshot.

Entity Framework Core: Query tags

Wrapping up

If you want to find out easily what query was generated by Entity Framework Core for given LINQ query and you want to be able to find queries easily from logs then query tags is the way to go. It doesn’t add much overhead to your application and it makes it easy to find generated queries from log files. If you are logging queries anyway then query tags are much smaller in size than SQL queries written to logs and therefore you don’t have to worry when using them.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    2 thoughts on “Using query tags with Entity Framework Core 2.2

    • May 9, 2019 at 6:22 pm
      Permalink

      Very cool, and a great idea! One question: shouldnt the text in the output window match the TagWith() expression? So _logger.LogInformation(“Front page: new photos”); should send “Front page: new photos” to the output window, instead of “New photos for front page”

    Leave a Reply

    Your email address will not be published. Required fields are marked *