58

Using query tags with Entity Framework Core 2.2

 5 years ago
source link: https://www.tuicool.com/articles/hit/iqQBfeb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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("Front page: new photos")
                                .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.

BjmIber.png!web

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK