How to log queries using Entity Framework 7?

前端 未结 10 1511
清歌不尽
清歌不尽 2020-12-15 23:55

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 genera

10条回答
  •  春和景丽
    2020-12-16 00:18

    I think I figured this out. With the current EF7 bits, ILoggerFactory is registered with the dependency injection container which EF is using. You can get a reference to the container, which is an IServiceProvider, via the ScopedServiceProvider property of DbContext when it is cast to IDbContextServices. From there, you can get the ILoggerFactory and configure it using the AddToConsole extension method from the Microsoft.Framework.Logging.Console NuGet package.

    public static void LogToConsole(this DbContext context)
    {
        // IServiceProvider represents registered DI container
        IServiceProvider contextServices = ((IDbContextServices)context).ScopedServiceProvider;
    
        // Get the registered ILoggerFactory from the DI container
        var loggerFactory = contextServices.GetRequiredService();
    
        // Add a logging provider with a console trace listener
        loggerFactory.AddConsole(LogLevel.Verbose);
    }
    

    Here is a gist I created for this snippet: https://gist.github.com/tonysneed/4cac4f4dae2b22e45ec4

提交回复
热议问题