EF Get SQL from Entity Framework 6

C#Entity Framework

Please contribute by voting. Thanks!

It's not always feasible to use SQL Server Profiler to get the raw SQL while working with Entity Framework 6 (and up) and LINQ. Also, sometimes you want to get the SQL from within your application layer. This is a really simple trick that let's you access the SQL before it gets sent to the database:

//Do this wherever you can access your database context, but before you execute your LINQ
context.Database.Log = sql => System.Diagnostics.Debug.WriteLine(sql);

The above code prints the SQL to the Output / Debug window in Visual Studio while you are running your application. You can set a breakpoint in the lambda to inspect the sql if you want to. The lambda function can be edited to do other stuff as well.

N.B. This method does not show the parameters provided to the SQL.

Article created: Aug 15 '19. Edited Aug 15 '19.

Your comment

You need to sign up / log in to comment this article


Created by Matt Hamilton [13] Aug 15 '19

Share article

Do you know about

Software architecture?

Write an article