EF Core 显示SQL语句

 

1. 使用 Nuget 引入如下两个包:

Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console

 

2. 在 DbContext.cs 中加入以下代码

        public static readonly LoggerFactory LoggerFactory = new LoggerFactory(new[] { new DebugLoggerProvider() });

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseLoggerFactory(LoggerFactory).UseMySql("server=xxx.xxx.xx.x;uid=xxx;pwd=...;database=xxx", x => x.ServerVersion("5.7.26-mysql"));
            optionsBuilder.EnableSensitiveDataLogging();
            optionsBuilder.EnableDetailedErrors();
            optionsBuilder.ConfigureWarnings(
                b => b.Log(
                    (RelationalEventId.ConnectionOpened, LogLevel.Information),
                    (RelationalEventId.ConnectionClosed, LogLevel.Information)));
        }

 

 

 

3. 运行后在输出中可以看到SQL语句

 

posted @ 2024-03-08 17:29  小丸  阅读(154)  评论(0编辑  收藏  举报