How to view/inspect the generated SQL by Entity Framework Core using .NET Core’s build-in logging

Referring: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0

This blog post is about how to view the SQL generated by Entity Framework Core. This method uses Microsoft’s built-in logging for .NET Core.

This method is an alternative to profiling the SQL with something like SQL Server Management Studio. This will work with an ASP.NET Core application, which should cover the vast majority of use cases!

By default, .NET Core outputs logs to the following locations when you call HostCreateDefaultBuilder(args) within Program.cs:

  • Console
  • Debug
  • Event Source
  • EventLog (Windows only)

Enable sensitive data logging

Open your startup file for your .NET Core project (Startup.cs). Now find where you’ve configured your application to use Entity Framework Core. This should be in the ConfigureServices method.

Enabling sensitive data logging allows you to view the parameters being passed into the SQL queries in the logs.

Configure the logging using your configuration file

Add the following string in your appsettings.json

  "Microsoft.EntityFrameworkCore.Database.Command": "Information",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

Result:

Now instead of @p1, @p2 etc the logging framework will log the complete parameters in plain text