Get generated SQL for a DbContext.SaveChanges in E

2020-04-21 02:27发布

In Entity Framework Core, is it possible to see the SQL that will be applied when the SaveChanges() method is called on the DbContext?

3条回答
我想做一个坏孩纸
2楼-- · 2020-04-21 03:03

you can use console logger "EF Core logging automatically integrates with the logging mechanisms of .NET Core " you can read about here : https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx

查看更多
家丑人穷心不美
3楼-- · 2020-04-21 03:07

You can use DbContextOptionsBuilder.UseLoggerFactory(loggerFactory) method to log all sql output.By using constructor Injection like below

public class DemoContext : ObjContext
{
    private readonly ILoggerFactory _loggerFactory;

    public DemoContext() { }

    public DemoContext(ILoggerFactory loggerFactory)
    {
        _loggerFactory = loggerFactory;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder.UseLoggerFactory(_loggerFactory);
    }
}

using (var context = new DemoContext(_loggerFactory))
{
    var Employees = context.Employee.ToList();
}

Or

I suggest a few other ways of viewing the SQL generated is to use reflection to create an ObjectQuery object and then call the ToTraceString() method to actually store the query results.

using (var context = new EntityContext())
{
    var query = context.Customers.Where(c => c.Id == 1); 
    var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();  
}

Use SQL Logging

Using The DbContext.Database.Log property can be set to a delegate for any method that takes a string.

Log SQL to the Console.

using (var context = new EntityContext())
{
    context.Database.Log = Console.Write; 
}

Log SQL to Visual Studio Output panel.

using (var context = new EntityContext())
{
    context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); 

}
查看更多
We Are One
4楼-- · 2020-04-21 03:07

Here are the docs on creating a LoggerFactory in Core 3. In short:

var loggerFactory = LoggerFactory.Create(builder =>
{
    builder
        .AddFilter("Microsoft", LogLevel.Warning)
        .AddFilter("System", LogLevel.Warning)
        .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
        .AddConsole()
        .AddEventLog();
});

You may need to add a reference to Microsoft.Extensions.Logging.Console.

Use the DbContextOptionsBuilder to enable logging for a context.

optionsBuilder.UseLoggerFactory(loggerFactory)

I'll repeat the warning from here:

It is very important that applications do not create a new ILoggerFactory instance for each context instance. Doing so will result in a memory leak and poor performance.

Therefore, they recommend using a singleton/global instance:

public static readonly ILoggerFactory MyLoggerFactory =
    LoggerFactory.Create(builder => { builder.AddConsole(); });
查看更多
登录 后发表回答