Diskdrive
Diskdrive

Reputation: 18825

Is it possible to see the SQL query of a LINQ command?

It would help me understand LINQ a little bit better that's all.

I tried using the SQL Profiler but I'm not sure how I can get it to show the actual SQL commands.

Upvotes: 5

Views: 233

Answers (6)

nerdybeardo
nerdybeardo

Reputation: 4675

If you add a watch to your variable in debug mode and the value of your object will be the SQL query.

Upvotes: 0

mattruma
mattruma

Reputation: 16677

You can also check out LinqPad ... you can create a standard Linq query and it will show you what it would look like leveraging expressions and standard Transact-Sql.

Upvotes: 0

Neil T.
Neil T.

Reputation: 3320

Use the Log property of the DataContext object:

using (var dc = new DataContext())
{
    dc.Log = Console.Out;  // Outputs the SQL statement to a System.IO.TextWriter object

    var customers = dc.Customers.Single(c => c.Customer_ID == 7);
}

Upvotes: 1

DaveE
DaveE

Reputation: 3637

In the Profiler's Trace Properties window, Events Selection tab: select "Show all events", then under the TSQL section, ensure SQL:StmtStarting or SQL:BatchStarting is checked, then make sure the TextData column is checked.

When you run your trace, the TextData column will contain the SQL.

Have to second ScottGu's blog post for this, and his blog in general.

Upvotes: 0

RPM1984
RPM1984

Reputation: 73102

If your using LINQ-SQL then the best way is to use SQL Profiler. Your probably missing something in your trace profiler. Turn everything on, see the trace, then modify the trace profile accordingly.

If your using LINQ-Entities then there is an ObjectQuery<T> extension method called .ToTraceString() which will give you the SQL that is to be executed on the server.

Upvotes: 0

Matthew
Matthew

Reputation: 10444

ScottGu's blog has a great post on the subject here: http://weblogs.asp.net/scottgu/archive/2006/09/01/Understanding-LINQ-to-SQL-Query-Translations.aspx

There is a query visualizer you can use by hovering over the object in the debugger.

Upvotes: 6

Related Questions