SQL lookup that LINQ generates

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 that LINQ generating SQL, I do this by commenting out ToList() and putting a breakpoint in the command after this LINQ statement, and then I can point it and read the SQL.

My question is: is this the correct way to get the generated SQL?

+7
c # linq
source share
3 answers

Yes, this is the right 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

+3
source share

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); } } 
+5
source share

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

+1
source share

All Articles