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.

Developer technologies .NET Entity Framework Core
Developer technologies C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.