Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

c# - How do you show underlying SQL query in EF Core?

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?

Update: Diego added "Microsoft.EntityFrameworkCore.Database.Command": "Information" to appsettings.Development.json. See How do you show underlying SQL query in EF Core? for more details.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...