Entity Framework Core (EF) converts expressions into SQL at runtime. In earlier versions, it was straight forward to get the SQL. In Entity Framework Core 3, you must access the SQL using ILogger. This article explains how to access the SQL generated and gives some example code to access the output of queries made behind the scenes. This article works with Entity Framework Core 3.

Note: M_icrosoft is about to release Entity Framework Core 5 soon. This version will have an easier method to get at the SQL. This is the interface method._

Many developers may feel uncomfortable if they do not know what SQL EF executes behind the scenes. There’s a good reason for this! Expressions may not map on to SQL very easily. You may end up executing SQL that doesn’t take advantage of indexes, or the expression may end up filtering records after the data was selected from the database. In older versions of EF you could use ToTraceString()but this no longer exists in EF Core 6.

There may even be other reasons to access the SQL. Perhaps your want to convert EF expressions to SQL. This is all possible in EF Core. Grab the full sample here.

The Basics

The key to making entity framework log SQL queries is to provide it with a logging factory:

#c# #database #aspdotnet #database #entityframework #entityframeworkcore #ilogger #linq #sql

How To Access SQL Generated By Entity Framework Core 3
1.85 GEEK