asp.net core 3.1 打印EFCore执行的sql

1、StartUp.cs类里定义个全局变量:

 

using Microsoft.Extensions.Logging;
        public static readonly ILoggerFactory MyLoggerFactory
= LoggerFactory.Create(builder =>
{
#if DEBUG
    builder.AddConsole();
#endif
});

2、ConfigureServices里添加Mysql上下文时,添加日志:

           // 添加mysql的dbcontext上下文
            services.AddDbContextPool<IDbContext, ApplicationDbContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("Default"), sqlOptions =>
                {
                    sqlOptions.EnableRetryOnFailure(3, TimeSpan.FromSeconds(30), new[] { 2 });
                }).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(MyLoggerFactory);
            }, 128);

 

3、第1步,我们只是在Debug模式下才打印,所以我们在F5运行之前,需要调整调试模式,不要选择 IIS Express,选择自己的项目web名称的那个,如下图:

 

4、接下来F5运行,打开页面的同时会有黑屏(类似CMD)的调试界面,会打印相应的日志,以及EFCore执行转换的sql脚步。

 

posted @ 2020-08-11 23:57  沐雪架构师  阅读(892)  评论(0编辑  收藏  举报