7

If I have a LINQ to SQL statement for example

var query = (from a in this.Context.Apples select a.Name).ToList();

When I want to see what SQL is being generated by LINQ, what I do is that I comment out the ToList() and put a breakpoint on the command after this LINQ statement and then I can hover it and read the SQL.

My question: Is that a correct way of getting the generated SQL?

Bohn
  • 26,091
  • 61
  • 167
  • 254

3 Answers3

5

You can also set the Log property of Your context to :

public class MyContext : DbContext{

  MyContext(){
        Database.Log = Console.WriteLine;
        //or like this 
        //Database.Log = message => Trace.TraceInformation(message);
  }
}
Marty
  • 3,485
  • 8
  • 38
  • 69
3

Yes, that's a correct way, but of course, there are others:

var context = new DataClasses1DataContext();

var sb = new StringWriter();
context.Log = sb;

var query = (from a in context.Persons select a.Name);

string s = query.ToString();
string command = context.GetCommand(query).CommandText;

//The log requires the query to actually hit the database
query.ToList();
string log = sb.ToString();

And also Linqpad:

enter image description here

Eduardo Wada
  • 2,606
  • 19
  • 31
1

You can also use SQL Server Profiler, add a trace, and see generated queries as they are being executed by the server.

Viktor A
  • 146
  • 8