Log Queries executed by Entity Framework DbContext

后端 未结 5 1802
夕颜
夕颜 2020-11-27 16:16

I\'m using EF 6.0 with LINQ in MVC 5 project. I want to log all the SQL queries executed by the Entity Framework DbContext for debugging/performance-measurement purpose.

5条回答
  •  孤街浪徒
    2020-11-27 17:02

    EF Core logging automatically integrates with the logging mechanisms of .NET Core. Example how it can be used to log to console:

    public class SchoolContext : DbContext
    {
        //static LoggerFactory object
        public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
                  new ConsoleLoggerProvider((_, __) => true, true)
            });
    
        //or
        // public static readonly ILoggerFactory loggerFactory  = new LoggerFactory().AddConsole((_,___) => true);
    
        public SchoolContext():base()
        {
    
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLoggerFactory(loggerFactory)  //tie-up DbContext with LoggerFactory object
                .EnableSensitiveDataLogging()  
                .UseSqlServer(@"Server=.\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");
        }
    
        public DbSet Students { get; set; }
    }
    

    If you would like to log to output window use this instead:

    public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
          new DebugLoggerProvider()
    });
    

    https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx

提交回复
热议问题