Log Queries executed by Entity Framework DbContext

asp.net-mvc-5 c# entity-framework entity-framework-6 linq

Question

I'm using EF 6.0 with LINQ in MVC 5 project. I want to log all the SQL queries executed by the Entity Framework DbContext for debugging/performance-measurement purpose.

In Java/Hibernate, equivalent behavior can be achieved by setting the property hibernate.show_sql=true. Is it possible to have a similar behavior in Entity Framework?

1
39
5/22/2014 10:52:54 AM

Accepted Answer

Logging and Intercepting Database Operations article at MSDN is what your are looking for.

The DbContext.Database.Log property can be set to a delegate for any method that takes a string. Most commonly it is used with any TextWriter by setting it to the “Write” method of that TextWriter. All SQL generated by the current context will be logged to that writer. For example, the following code will log SQL to the console:

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

    // Your code here...
}
59
5/22/2014 10:56:23 AM

Popular Answer

You can use this line to log the SQL queries to the Visual Studio "Output" window only and not to a console window, again in Debug mode only.

public class YourContext : DbContext
{   
    public YourContext()
    {
        Database.Log = sql => Debug.Write(sql);
    }
}


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