7

Is it possible to get the generated SQL from a compiled linq query?

dcarneiro
  • 7,060
  • 11
  • 51
  • 74

3 Answers3

9

You can:

  1. Use the log property of the context to redirect the generated query to the output window of Visual Studio. link
  2. Or use the LINQ to SQL Debug Visualizer. link
jfs
  • 16,758
  • 13
  • 62
  • 88
  • redirecting the log to Visual Studio output was the easier way. Thumbs up – dcarneiro Apr 08 '11 at 11:00
  • 1
    For the benefit of future googlers. I couldn't find anything relevant to the question on the first link. The content must have changed since this answer was posted. You basically add `db.Log = Console.Out;` where db is your database context object. [see source on msdn](http://msdn.microsoft.com/en-us/library/bb386961.aspx) – Chris B Jul 01 '13 at 11:54
2

Use LinqPad :

Or alternatively get use sql server profiler to watch the query. I know you used to be able to however over the query variable in debug and it would show you the query it is going to execute but I am not entirely sure if that still works (Definitely not on client side apps)

TBohnen.jnr
  • 5,117
  • 1
  • 19
  • 26
0

Thanks jfs, but the link in your option #1 is not good anymore. It is not showing any relevant article. Chris B's link to the MSDN article helped me.

Here is my solution since mine is not a Console application:

TextWriter tw = new StringWriter();
db.Log = tw;
IQueryable<Customer> custQuery =
    from cust in db.Customers
    where cust.City == "London"
    select cust;

string output = tw.ToString();   
// output variable has the generate SQL now
Sagar
  • 579
  • 5
  • 7