Get generated SQL for a DbContext.SaveChanges in Entity Framework Core

entity-framework-core

Question

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

1
1
5/26/2019 6:17:35 AM

Accepted Answer

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

1
5/26/2019 7:47:55 AM

Popular Answer

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); 

}


Related Questions





Related

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