The log of using Entity Framework Core in ASP.NET Core shows sql statement

In development, we want to view the SQL statements executed by EF Core during debugging. You can use the SQL Studio Manager Tools tool. Another way is to use the logs provided by EF Core.
Steps to use Entity Framework Core logs in ASP.NET Core:

1. Set the startup method

Delete the IIS node in launchSettings.json to start the program as a console application.

2. Configure logs in 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<Startup>();
                });
    }
}

3. The default log does not display sensitive data, so you cannot see the parameters of the SQL statement execution. If you want to see the parameters, you need to enable the display of sensitive data in the ConfigureServices method of Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext<CompanyDbContext>(options => {
        //启用显示敏感数据
        options.EnableSensitiveDataLogging(true);
        options.UseSqlServer(Configuration.GetConnectionString("CompanyDbContext"));
    }); 
}

4. Configure appsettings.json log options:

{
  "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"
  }
}
Published 177 original articles · 61 praises · 170,000 views

Guess you like

Origin blog.csdn.net/xingkongtianyuzhao/article/details/104304788