How do you show underlying SQL query in EF Core 2.0?

c# entity-framework-core

Question

At 3:15 from the end of this ".NET Core 2.0 Released!" video, Diego Vega shows a demo of new features in Entity Framework Core 2.0. As part of that, a dump of the underlying SQL is shown in the console app.

enter image description here

I have seen many answers on Stack Overflow suggesting that people use an SQL profiler to view the underlying queries. But now I'm curious: how can you do what Diego Vega did, and get the query to show right there in the application?

1
34
6/26/2018 9:58:45 AM

Accepted Answer

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");
14
4/13/2019 9:02:56 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow