EF Core logging issue

Mirza 20 Reputation points
2023-10-11T11:25:44.6133333+00:00

I installed Microsoft.Extensions.Logging.Debug according to the tutorial and wanted to see how each query statement of ef core is converted into sql.

And added the following code in Context:

public partial class MyDbnContext : DbContext
{
         [Obsolete]
         public static readonly LoggerFactory LoggerFactory = new LoggerFactory(new[] { new DebugLoggerProvider((_, __) => true) });
         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
         {
             base.OnConfiguring(optionsBuilder);
             optionsBuilder.UseLoggerFactory(LoggerFactory);
         }
}

But every time the query statement is executed, the corresponding sql statement does not appear.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
702 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,390 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,201 Reputation points
    2023-10-11T21:31:33.41+00:00

    For ASP.NET Core or Razor Pages

    In Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
    
            // Add services to the container.
            builder.Services.AddRazorPages();
    
            builder.Services.AddDbContext<Context>(options =>
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
                    .EnableSensitiveDataLogging());
    

    ScreenshotLog1

    Windows forms or Console project

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=NorthWind2022;Integrated Security=True")
            .EnableSensitiveDataLogging()
            .LogTo(message => Debug.WriteLine(message),
                new[] { DbLoggerCategory.Database.Command.Name },
                LogLevel.Information);
    

    Screenshot

    Log2

    NuGet packages in project file

    <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.10" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="7.0.10" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.10" />
    </ItemGroup>
    

    Better Logging with SeriLog

    See the following

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful