How do I view the SQL generated by entity framework ?
(In my particular case I\'m using the mysql provider - if it matters)
My answer addresses EF core. I reference this github issue, and the docs on configuring DbContext:
Simple
Override the OnConfiguring
method of your DbContext
class (YourCustomDbContext
) as shown here to use a ConsoleLoggerProvider; your queries should log to the console:
public class YourCustomDbContext : DbContext
{
#region DefineLoggerFactory
public static readonly LoggerFactory MyLoggerFactory
= new LoggerFactory(new[] {new ConsoleLoggerProvider((_, __) => true, true)});
#endregion
#region RegisterLoggerFactory
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLoggerFactory(MyLoggerFactory); // Warning: Do not create a new ILoggerFactory instance each time
#endregion
}
Complex
This Complex case avoids overriding the DbContext OnConfiguring method. , which is discouraged in the docs: "This approach does not lend itself to testing, unless the tests target the full database."
This Complex case uses:
IServiceCollection
in Startup
class ConfigureServices
method
(instead of overriding the OnConfiguring
method; the benefit is a looser coupling between the DbContext
and the ILoggerProvider
you want to use)ILoggerProvider
(instead of using the ConsoleLoggerProvider
implementation shown above; benefit is our implementation shows how we would log to File (I don't see a File Logging Provider shipped with EF Core))Like this:
public class Startup
public void ConfigureServices(IServiceCollection services)
{
...
var lf = new LoggerFactory();
lf.AddProvider(new MyLoggerProvider());
services.AddDbContext(optionsBuilder => optionsBuilder
.UseSqlServer(connection_string)
//Using the LoggerFactory
.UseLoggerFactory(lf));
...
}
}
Here's the implementation of a MyLoggerProvider
(and its MyLogger
which appends its logs to a File you can configure; your EF Core queries will appear in the file.)
public class MyLoggerProvider : ILoggerProvider
{
public ILogger CreateLogger(string categoryName)
{
return new MyLogger();
}
public void Dispose()
{ }
private class MyLogger : ILogger
{
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter)
{
File.AppendAllText(@"C:\temp\log.txt", formatter(state, exception));
Console.WriteLine(formatter(state, exception));
}
public IDisposable BeginScope(TState state)
{
return null;
}
}
}