Get SQL query from LINQ to SQL?

James123 picture James123 · Aug 14, 2013 · Viewed 81.6k times · Source

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);

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Aug 14, 2013

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.