How do you show underlying SQL query in EF Core?
Hi you can do something like following to display Entity Framework Core generated sql code in output window.
In your DbContext
class:
public static readonly Microsoft.Extensions.Logging.LoggerFactory _myLoggerFactory =
new LoggerFactory(new[] {
new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider()
});
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_myLoggerFactory);
}
The debug logger writes messages in the debug output window only when a debugger is attached.
You will have to do following:
- using Microsoft.Extensions.Logging;
- Install nuget package: Microsoft.Extensions.Logging.Debug
Just add "Microsoft.EntityFrameworkCore.Database.Command": "Information"
to appsettings.Development.json so it's only logged in dev mode. You typically don't want to log every query in a production app.
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDB-2;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
,"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"AllowedHosts": "*"
}
The SQL output shows in the command window or VS output window.
See SQL Logging of Entity Framework Core in the official docs. It's a bug that it doesn't log by default, see this GitHub issue.
I use EF Core 3.x, this works for me:
services.AddDbContext<LibraryContext>(options => options
.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()))
.UseSqlServer(Configuration.GetConnectionString("LibraryDemoSql")));
Credit: https://stackoverflow.com/a/59663606/2185783
https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging
In the OnConfiguring method of DbContext
you can set your logger, log in console is a predefined type, just use this NuGet. Note that using Factory pattern is a best practice for the logger instances.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");