Skip to main content

Tracking SQL statements generated by Entity Framework

With Entity Framework 6, we now have the ability to view the SQL statements generated by Entity Framework. This would be useful for debugging database issues or optimizing queries. In the constructor, you may simply attach to the Log Action where you can be notified on SQL statements being executed.

    public class ExampleDatabase : DbContext
    {
        public ExampleDatabase()
            : base("Example")
        {
            Database.Log = sql => Debug.WriteLine(sql);
        }

        public DbSet<Person> Persons { get; set; }

        public DbSet<Audit> Audits { get; set; }

The following code uses Debug.WriteLine to output the SQL statements generated. In Visual Studio, this would be output to the Debug pane of the Output window. Let's take a look at a sample output.

Opened connection at 2/19/2015 2:38:25 PM -06:00

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[__MigrationHistory] AS [Extent1]
        WHERE [Extent1].[ContextKey] = @p__linq__0
    )  AS [GroupBy1]


-- p__linq__0: 'EFChangeTracker.ExampleDatabase' (Type = String, Size = 4000)

-- Executing at 2/19/2015 2:38:28 PM -06:00

-- Completed in 61 ms with result: SqlDataReader



Closed connection at 2/19/2015 2:38:28 PM -06:00

Not only would you be able to view the SQL statements, and SQL input parameters, you also have how long it takes to execute the SQL statement. Perfect!

Comments