C# 如何在EF Core中显示底层SQL查询?
在本视频结束后3:15,Diego Vega展示了Entity Framework Core 2.0中的新功能演示。作为其中的一部分,控制台应用程序中显示了底层SQL的转储 我已经看到许多关于堆栈溢出的答案,建议人们使用SQL分析器来查看底层查询。但现在我很好奇:你怎么能像Diego Vega那样,让查询显示在应用程序中C# 如何在EF Core中显示底层SQL查询?,c#,entity-framework-core,C#,Entity Framework Core,在本视频结束后3:15,Diego Vega展示了Entity Framework Core 2.0中的新功能演示。作为其中的一部分,控制台应用程序中显示了底层SQL的转储 我已经看到许多关于堆栈溢出的答案,建议人们使用SQL分析器来查看底层查询。但现在我很好奇:你怎么能像Diego Vega那样,让查询显示在应用程序中 更新:迭戈在appsettings.Development.json中添加了“Microsoft.EntityFrameworkCore.Database.Command”:
更新:迭戈在appsettings.Development.json中添加了“Microsoft.EntityFrameworkCore.Database.Command”:“信息”。有关更多详细信息,请参阅。您好,您可以执行以下操作,在输出窗口中显示实体框架核心生成的sql代码。 在
DbContext
类中:
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);
}
调试记录器仅在附加调试程序时才在“调试输出”窗口中写入消息
您必须执行以下操作:- 使用Microsoft.Extensions.Logging李>
- 安装nuget软件包:Microsoft.Extensions.Logging.Debug
DbContext
的onconfigurang方法中,您可以设置记录器,登录控制台是预定义的类型,只需使用。请注意,使用工厂模式是记录器实例的最佳实践
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");
我确信被接受的答案是有效的,但我想知道如何使用DI来做到这一点,所以
private readonly ILoggerFactory loggerFactory;
public MyDataContext(DbContextOptions<MyDataContext> options, ILoggerFactory loggerFactory)
: base(options)
{
this.loggerFactory = loggerFactory;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Allow null if you are using an IDesignTimeDbContextFactory
if (loggerFactory != null)
{
if (Debugger.IsAttached)
{
// Probably shouldn't log sql statements in production
optionsBuilder.UseLoggerFactory(this.loggerFactory);
}
}
}
专用只读iLogger工厂Logger工厂;
公共MyDataContext(DbContextOptions选项,ILoggerFactory loggerFactory)
:基本(选项)
{
this.loggerFactory=loggerFactory;
}
配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
{
//如果使用的是IDesignTimeDbContextFactory,则允许null
if(loggerFactory!=null)
{
if(Debugger.IsAttached)
{
//可能不应该在生产中记录sql语句
选项builder.UseLoggerFactory(this.loggerFactory);
}
}
}
如果您正在编写基于ASP.NET核心MVC框架的API或应用程序服务,您可以像下面这样在Startup.cs
类中启用SQL日志记录
public void ConfigureServices(IServiceCollection services)
{
...
Action<DbContextOptionsBuilder> dbOptionsContextBuilder = builder =>
{
builder.UseSqlServer(Configuration.DbConnection) // Configuration.DbConnection is the db connection string
.UseLoggerFactory(ConsoleLoggerFactory); // Logs out SQL
};
services.AddDbContext<YourDatabaseContext>(dbOptionsContextBuilder);
...
}
我使用EF Core 3.x,这对我很有用:
services.AddDbContext<LibraryContext>(options => options
.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()))
.UseSqlServer(Configuration.GetConnectionString("LibraryDemoSql")));
services.AddDbContext(选项=>options
.UseLoggerFactory(LoggerFactory.Create(builder=>builder.AddConsole())
.UseSqlServer(Configuration.GetConnectionString(“LibraryDemoSql”));
信用证:这里的许多答案都很有魅力,但如果您使用的是NLog,则不会 如果您像我一样使用NLog,您可以:
optionsBuilder.UseLoggerFactory(new NLogLoggerFactory());
在.Net Core 3中登录到visual studio中的输出窗口 使用
AddDebug
写入输出调试窗口
services.AddDbContext<LibraryContext>(options => options
.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug()))
.UseSqlServer(Configuration.GetConnectionString("key")));
services.AddDbContext(选项=>options
.UseLoggerFactory(LoggerFactory.Create(builder=>builder.AddDebug())
.UseSqlServer(Configuration.GetConnectionString(“key”));
如果您使用的是Serilog:
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", Serilog.Events.LogEventLevel.Information)
.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose))
只需将“Microsoft.EntityFrameworkCore.Database.Command:”信息“添加到appsettings.Development.json,这样它就只在开发模式下登录。您通常不希望在生产应用程序中记录每个查询
{
"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": "*"
}
SQL输出显示在命令窗口或VS输出窗口中
见官方文件。这是一个默认情况下不会记录的错误,请参阅。显然他正在使用,很可能是使用过滤器
if(eventId.Id==Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.CommandExecuted.Id)
只需添加“Microsoft.EntityFrameworkCore.Database.Command”:“信息”到appsettings.Development.json如果您首先使用数据库(Scaffold DbContext
),并且您的DbContext
将被重新生成,这将覆盖您对on配置所做的任何更改,这很简单。所有其他解决方案都不必要地复杂。谢谢,下面请看我的答案:只需将“Microsoft.EntityFrameworkCore.Database.Command”:“Information”添加到appsettings.Development.json,这样它就只在开发模式下登录。你知道如何使用Serilog吗?你在哪里可以看到SQL查询?我在输出窗口中看不到它。您好@Muflix,这取决于您在哪里运行它。我的应用程序是一个Web API应用程序,我在Rider的IIS Express配置中运行它,SQL日志显示在“运行”窗口中。@maximus,谢谢您的确认!这让我意识到我需要将我的项目->属性->调试->启动设置更改为Project,而不是IIS Express。现在,我打开了“控制台”窗口来查看查询。更简单的方法是,请参见下面的答案:只需将“Microsoft.EntityFrameworkCore.Database.Command”:“信息”添加到appsettings.Development.json,这样它就只在开发模式下登录。输出窗口是“调试”。控制台是作为控制台应用程序运行时的控制台窗口。更简单的方法是,请参阅下面我的答案:只需将“Microsoft.EntityFrameworkCore.Database.Command”:“Information”添加到appsettings.Development.json,这样它就只在开发模式下登录。这是我的最佳答案。最后非常感谢!很久以来,我一直在寻找这个问题的答案。到目前为止,这是最简单的解决方案。你知道如何使用Serilog吗?
{
"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": "*"
}