sql-serverentity-frameworksql-server-profiler

How to profile Entity Framework activity against SQL Server?


It's easy to use SQL Server Profiler to trace stored procedures activity. But how to trace SQL queries issued by LINQ via Entity Framework? I need to identify such queries (LINQ code) that consume a lot of time, are called most frequently and therefore are the first candidates for optimization.


Solution

  • I've found useful DbContext.Database.Log property.

    MSDN article Logging and Intercepting Database Operations

    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...
    }
    

    What gets logged?

    When the Log property is set all of the following will be logged: