I am using Entity Framework Core and I need to see which SQL code is being generated. In previous versions of Entity Framework I could use the following:
string sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
Where query is an IQueryable object ... But ToTraceString is not available in EF Core.
How can I do something similar in EF Core?
For EF Core 2.1.2 you can use this.
For EF Core 3.0
see Gist from RosiOli
For EF Core 3.1
The issue is also tracked by the EF net core team and is scheduled for the next release.
As a public service:
And then these extension methods (IQueryableExtensions1 for .NET Core 1.0, IQueryableExtensions for .NET Core 2.0) :
My take based on @nikolay-kostov answer.
The difference is that I get the SQL command with parameters extracted instead of hard coded which is more in line with how EF Core send commands to the database. Also, if you want to edit and send the command to the database, it is a better practice to use parameters.
For anyone just trying to diagnose a one-off misfiring EF Core query or the like and not wanting to change their code, there are a couple of options:
Use SQL Server Management Studio (SSMS) SQL Profiler
If you've got SQL Server Management Studio (SSMS) installed you can just fire up the SQL Profiler from the Tools menu in SSMS:
And then start a new trace running in SQL Profiler once it opens.
You'll then be able to see the incoming SQL request from EF, they are generally pretty well formed and easy to read.
Check the Output Window in Visual Studio
In my copy of VS2019, using EF2.2 I can change the output window to show the output from the Web Server (select the name of your app and web server in the "Show output from" combo at the top of the Output pane) and the outgoing SQL is also shown in there. I've checked my code and as far as I can see I haven't done anything to enable that, so I think it must do this by default:
Since EF 7 is renamed to Entity Framework Core I will summarize you the options for EF Core.
There are 3 approaches for logging SQL statements from
IQueryable<>
:Here is the crazy reflection code (extension method):
After adding this extension method to your code, you can use the method as follows:
Referral: http://rion.io/2016/10/19/accessing-entity-framework-core-queries-behind-the-scenes-in-asp-net-core/ and https://gist.github.com/rionmonster/2c59f449e67edf8cd6164e9fe66c545a
Updated: Edited so that EF Core 2.1 is supported
Adding this answer because all the suggestions here have broken with new EF Core releases (ie, all the answers here are broken on EF Core 2.2). Here's code that worked for me on the first try, and seems to be .NET Core version agnostic (so far): https://blogs.msdn.microsoft.com/dbrowne/2017/09/22/simple-logging-for-ef-core/