View Generated SQL in Entity Framework (EF)

Hey everyone,

Just a quick post on how to view the generated sql in entity framework. To start with, just add the following line to your db context constructor:

public class TestDbContext : DbContext
    {
        public TestDbContext() : base("name=TestDbContext")
        {
            this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); //This line
        }
        ...

With this line added, you should now be able to see all of your generated sql in the output window.

SELECT TOP (1) 
    [Project1].[VidId] AS [VidId], 
    [Project1].[CreatedAt] AS [CreatedAt], 
    [Project1].[Check] AS [Check], 
    [Project1].[SourceCheck] AS [SourceCheck]
    FROM ( SELECT 
        [Extent1].[VidId] AS [VidId], 
        [Extent1].[CreatedAt] AS [CreatedAt], 
        [Extent1].[Check] AS [Check], 
        [Extent1].[SourceCheck] AS [SourceCheck]
        FROM [dbo].[Vids] AS [Extent1]
        WHERE [Extent1].[VidId] < @p__linq__0
    )  AS [Project1]
    ORDER BY [Project1].[VidId] DESC

-- p__linq__0: '535' (Type = Int32)
-- Executing at 28/06/2014 5:00:16 PM +10:00
-- Completed in 0 ms with result: SqlDataReader

If you’re not using EF6, there were a few other options where I came across this solution: http://stackoverflow.com/a/20751723/522859


Posted

in

, ,

by

Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: