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?
You could run the SQL Server Profiler. If you use SQL profiler, to ensure capture of all LINQ queries from your VS debug session, use SQL Profiler 'RPC Completed' and 'SQL:BatchCompleted' events.
To view the SQL that will be generated, simply call ToTraceString() . You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query. You can attach a tracer to your SQL server of choice, which will show you the final query in all its gory detail.
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);
}
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With