Skip to content

Printing the SQL generated by EF Core

Notifications You must be signed in to change notification settings

TomasHubelbauer/ef-sql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 

Repository files navigation

EF Core Query SQL

This is a repository dedicated to testing out a reflection-based snippet for printing SQL generated from a EF Core query LINQ expression.

The snippet code can be found in multiple places with comments worth following for updated versions:

Let's create the test application and include the EF code NuGet packages:

dotnet new console
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

For the classes see, AppDbContext, User, Car and Trip in code.

Console.WriteLine(appDbContext.Users.Include(u => u.Car).Where(u => u.Car != null).ToSql());
SELECT [u].[Id], [u].[CarId], [u].[Name], [u.Car].[Id], [u.Car].[Make], [u.Car].[Model]
FROM [Users] AS [u]
INNER JOIN [Cars] AS [u.Car] ON [u].[CarId] = [u.Car].[Id]
WHERE [u].[CarId] IS NOT NULL

To-Do

Turn this into a hosted app (Azure Function?) and offer it as a tool for the dev community

Mention the detailed logging option which shows the executed SQL statements