3 Ways to View and Log the SQL Generated by Entity Framework Core 5

Ok, so you're using Entity Framework Core as your ORM but you want to know what SQL it's sending to your database? The team showed 3 ways of doing this during NET Conf 2020 while demonstrating Entity Framework Core 5 functionality.

You can check out the replays from .NET Conf  right here on Youtube.


1.Debug View

For use this, you're going to want to set a breakpoint below your EF Core query.

Breakpoint hit after the query.

Once the breakpoint is hit hover over query to expand then click on > Debug View > The dropdown beside the magnifying glass> Text Visualizer.

Click on the Text Visualizer Option here to see the SQL created by Entity Framework Core 5

There you have it, the SQL that will be sent to the database.

Text Visualizer option showing the query generated by EF Core 5.

2. ToQueryString() Method

For this, you'll want to create a variable using the query.ToQueryString() method. Then you can do write it to the console.

Using the ToQueryString() method to write the query to the console. 

Now you'll be able to view the SQL generated by entity framework core in the output from the Web Server:

Output from the webserver showing the SQL 

3. Logging with LogTo()

The first two options don't scale well, that's where LogTo() comes in. Here's a way that you can log the SQL generated from EF Core 5.

Add the method LogTo() where you've configured Entity Framework Core. It takes an action and a logging level. Here I'm just writing it to the console and setting the log level to Information.

Setting up logging for entity framework 5 using the LogTo() method.

Again, we'll see the SQL logged to the output window.

Output from the webserver showing the SQL generated by EF Core 5.

In the comments below, Eli Black sent me a tip. If you already have a logger registered (as they did) you may have to alter the LogTo() method.

Instead of writing LogTo(Console.WriteLine, LogLevel.Information) you may have to do something like:

.LogTo((message) => logger.LogWarning("SQL {sqlTrace}", message), ...)

Thanks to Eli for the tip

If you're still on EF Core 3.0, you can use the method I demonstrate in this post.