在ASP.NET Core使用Entity Framework Core的日志显示sql语句 您所在的位置:网站首页 eclipse不输出打印语句 在ASP.NET Core使用Entity Framework Core的日志显示sql语句

在ASP.NET Core使用Entity Framework Core的日志显示sql语句

2024-07-17 22:57| 来源: 网络整理| 查看: 265

在开发中,我们想在调试中查看EF Core执行的sql语句,可以使用SQL Studio Manager Tools工具,另一种方式是使用EF Core提供的日志。 在ASP.NET Core使用Entity Framework Core的日志的步骤:

1. 设置启动方式

在launchSettings.json中删除IIS节点,使程序以控制台应用启动。

2. 在Programm.cs配置日志 using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace CompanyApp { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddEventSourceLogger(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); } } 3. 默认日志不显示敏感数据,这样查看不到sql语句执行的参数,如果想看到参数,需要在Startup.cs的ConfigureServices方法中启用显示敏感数据: public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext(options => { //启用显示敏感数据 options.EnableSensitiveDataLogging(true); options.UseSqlServer(Configuration.GetConnectionString("CompanyDbContext")); }); } 4. 配置appsettings.json日志选项: { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "CompanyDbContext": "Server=(localdb)\\mssqllocaldb;Database=CompanyDb;Trusted_Connection=True;MultipleActiveResultSets=true" } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有