How to log queries using Entity Framework 7?

entity-framework entity-framework-core


I am using Entity Framework 7 on the nightly build channel (right now I'm using version EntityFramework.7.0.0-beta2-11524) and I'm trying to log the queries that EF generates just out of curiosity.

I'm writing a simple console program, I tried using the same logging technic that EF6 uses, but DbContext.Database.Logis not available on Entity Framework 7. Is there a way to log or just take a peek at the SQL generated by EF7?

1/17/2016 11:34:49 AM

Accepted Answer

For those using EF7 none of the above worked for me. But this is how i got it working. (from @avi cherry's comment)

In your Startup.cs you proably have a Configure method with a bunch of configurations in it. It should look like below (in addition to your stuff).

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        //this is the magic line
        loggerFactory.AddDebug(LogLevel.Debug); // formerly LogLevel.Verbose

        //your other stuff

11/16/2016 7:12:23 PM

Popular Answer

You can log to the console using this code, I am sure it will be wrapped in a simpler api later:

using System;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Utilities;
using Microsoft.Framework.Logging;

public static class SqlCeDbContextExtensions
    public static void LogToConsole(this DbContext context)
        var loggerFactory = ((IAccessor<IServiceProvider>)context).GetService<ILoggerFactory>();
        loggerFactory.AddProvider(new DbLoggerProvider());

And the DbLoggerProvider is implemented here:

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow