Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeing the SQL that LINQ generates [duplicate]

Tags:

c#

linq

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?

like image 999
Bohn Avatar asked Jan 21 '16 23:01

Bohn


People also ask

How can I see SQL query generated by LINQ in Visual Studio?

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.

How do I see the actual SQL query generated by Entity Framework Core?

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.


2 Answers

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);
  }
}
like image 159
Marty Avatar answered Nov 11 '22 03:11

Marty


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

like image 22
Eduardo Wada Avatar answered Nov 11 '22 01:11

Eduardo Wada