Byron Sommardahl
Byron Sommardahl

Reputation: 13012

How can I see the SQL that is created from a LINQ to SQL query?

How can I see the SQL that is created from a LINQ to SQL query? The obvious answer is to open up the SQL profiler and look at it there. Is there a way in VS?

Maybe there is a VS add-on like a visualizer that allows you to hover over the DataContext to view the SQL.

Upvotes: 3

Views: 112

Answers (3)

Kane
Kane

Reputation: 16812

In addition to @Mark's answer you might want to look at LINQPad which could be useful if you're writing a large amount of LINQ queries.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839144

Yes, you can evaluate:

query.Expression.ToString()

You can also see this string in the debugger in Visual Studio when you examine the query variable. You don't need a plugin.

Note that it's a property of the query, not the DataContext.

Upvotes: 5

casperOne
casperOne

Reputation: 74560

You can set a TextWriter instance (which means anything derived from TextWriter, since it is an abstract class) to the Log property on the DataContext. When the statements are executed against SQL Server, the same statements will be written to the TextWriter you set on the Log property.

This also applies for insertions, updates, and deletes that are performed with that DataContext as well.

Upvotes: 2

Related Questions