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.
Once the breakpoint is hit hover over query to expand then click on > Debug View > The dropdown beside the magnifying glass> Text Visualizer.
There you have it, the SQL that will be sent to the database.
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.
Now you'll be able to view the SQL generated by entity framework core in the output from the Web Server:
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.
Again, we'll see the SQL logged to the output window.
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.
Comments