58

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);
2
  • 7
    LinqPad would also allow you to see the SQL and run the SQL directly Commented Aug 14, 2013 at 17:09
  • For Entity Framework Core => stackoverflow.com/a/44180537/2736742 Commented Nov 21, 2019 at 14:13

4 Answers 4

90

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Out of curiosity, is there a way to do it programmatically?
SQL Profiler or Entity Framework Profiler needs run on SQL server machine or my local machine?
@James123 you can run both on local machine
Never heard of the Entity Framework Profiler before. Do you have any links to it?
For those using Entity Framework 6 check this, hope helps someone.
16

Incidentally, LINQ to SQL is not entity framework. If the former, you can set [yourDataContext].Log = Console.Out (or some other stream writer) and get the query.

In the query you have, consider writing it as follows to be able to do the ToString trick:

var committeeMemberQuery =
           db.Committee_Member.*WHERE*
           (x => 
              x.Customer_Number == activity.Contact.Number
                 && x.Position_Start_Date.Value.Year == activity.EndDate
                 && x.Committee_Id == activity.Committee.Id && x.Cancelled != 1
           );

var committeeMember = committeeMemberQuery.FirstOrDefault();

Now you can do committeeMemberQuery.ToString() however you will not get parameter info (you will with DataContext.Log = Console.Out but again, that's not Entity Framework, it's LINQ to SQL.

5 Comments

I added a link to some other implementations. IMO, the "other streamwriter" option is better than the highest voted answer, because that option allows you to see the sql generated for insert/update operations that get generated when calling DataContext.SubmitChanges.
[yourDataContext].Database.Log = <streamwriter>, if you are using DbContext.
EF 6 has this: public Action<string> Log { get; set; }
Why are there asterisks around "WHERE"? That's super confusing
I'm emphasizing that instead of putting the predicate inside the FirstOrDefault call, it's been pulled out into a Where call. There's no way to add additional formatting to code, AFAICT
2

See https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/how-to-display-linq-to-sql-commands for another approach to extract SQL command from linq.

More precisely, the following snippet shows the use case

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

var q =
    from cust in db.Customers
    where cust.City == "London"
    select cust;

DbCommand dc = db.GetCommand(q);

Console.WriteLine("\nCommand Text: \n{0}",dc.CommandText);
Console.WriteLine("\nCommand Type: {0}",dc.CommandType);
Console.WriteLine("\nConnection: {0}",dc.Connection);

Console.ReadLine();

Gives an ouput

Command Text:  
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactT  
itle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Coun  
try], [t0].[Phone], [t0].[Fax]  
FROM [dbo].[Customers] AS [t0]  
WHERE [t0].[City] = @p0  

Command Type: Text  

Connection: System.Data.SqlClient.SqlConnection

Comments

2

I know this is old, but for anyone using VS2022: In debug mode...

Step 1: Set a breakpoint at the statement that comes after the query.

Step 2: When your debug mode hits the breakpoint, hover over the variable which the query inserts values to. A gray box will show up with the object data. You can click the little triangle for more options.

Step 3: Look at the dropdown for Debug view and you can simply just view the query.

That's it! You can copy and paste that query into SSMS and run it on your database to see what the result should be, just be sure to refresh your database first if you are editing data in your test or method when you hit the breakpoint.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.