Using Query Tags With Entity Framework Core 2.2
A quick tutorial on how to use query tags to make working with queries and their logs easier.
Join the DZone community and get the full member experience.Join For Free
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 an application in the development box, it's possible to live without query tags. We can set breakpoints to see SQL code generated from LINQ queries. But how can we find queries from log files in multithreaded or multiuser scenarios?
Finding Queries From Logs Without Query Tags
But what if the site has multiple users at the 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 something like this in the logs:
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 logs like this probably raises a question: how can we match the information in the message above with SQL queries in the logs?
Applying Query Tags
Query tags make it easy to answer this question, as query descriptions are always generated with a SQL query. Use query tags like the following example shows.
model.NewPhotos = await _dataContext.Photos.TagWith("New photos for frontpage") .ProjectTo<PhotoListModel>() .ToListAsync();
TagWith() extension method you can be sure that the query description is always logged with the query. You can see query tags in action in the following screenshot.
If you want to find out what query was generated by Entity Framework Core for the given LINQ query and you want to be able to find queries from logs, then query tags is the way to go. They don't add much overhead to your application and they make 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.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.