Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get SQL query from LINQ to SQL?

I have a query which I am passing byte[] as a parameter. I am trying to get the SQL query out of it and run that query in management studio to debug. How can I extract the SQL statement from it?

 committeeMember =            db.Committee_Member.FirstOrDefault(x => x.Customer_Number == activity.Contact.Number            && x.Position_Start_Date.Value.Year == activity.EndDate            && x.Committee_Id == activity.Committee.Id && x.Cancelled != 1); 
like image 363
James123 Avatar asked Aug 14 '13 16:08

James123


People also ask

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

How do I see generated SQL from a LINQ query in Visual Studio?

If you are executing the linq query against a database, you can run the SQL Profiler to record the SQL query that is being executed.

How can I see the LINQ query in SQL Profiler?

Now, let's run the Application and run the trace in SQL Server Profiler. Click on Get Data button, the data will be populated on the page. Go to SQL Server Profiler and stop the trace, where you will see T-SQL statement of our stored procedure, as shown below. Notice that GetEmployees stored procedure is executed.


1 Answers

In debugger hover mouse over commiteeMember variable - it will show generated SQL query:

enter image description here

This is what ToString() returns for query. You can get same generated SQL query manually by calling ToString:

string sql = committeeMember.ToString(); 

This overridden method internally calls ObjectQuery.ToTraceString() which returns commands that will run on data source.


Also you can use SQL Profiler or Entity Framework Profiler to see which SQL query was executed.

like image 121
Sergey Berezovskiy Avatar answered Sep 22 '22 14:09

Sergey Berezovskiy