Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log Queries executed by Entity Framework DbContext

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?

like image 554
PC. Avatar asked May 22 '14 10:05

PC.


People also ask

How do I see the query generated by Entity Framework?

To view the SQL that will be generated, simply call ToTraceString() . You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query.

Which property can be leveraged to log and track queries with the Entity Framework using a DbContext object?

Database. Log property to log the SQL generated by DbContext . The Log property is of Action<string> type, so you can attach a delegate method with the string parameter and return void .

How can I see SQL query generated by LINQ in Visual Studio?

If you are executing the linq query against a database, you can run the SQL Profiler to record the SQL query that is being executed.


2 Answers

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... } 
like image 156
Andrew Avatar answered Sep 21 '22 03:09

Andrew


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);     } } 
like image 25
Dennis Mieszala Avatar answered Sep 17 '22 03:09

Dennis Mieszala