How to view the generated SQL Query of LINQ

Have you ever thought of viewing generated SQL query of LINQ you write? You may need the generated query for the debugging and the logging purposes. In this post let us see how to print the generated SQL query on the console.

Let us consider you have written LINQ as follows:

            DataClasses1DataContext context = new DataClasses1DataContext();
            IEnumerable<Order> result = context.Orders;
            var product = result.Where(x => x.OrderID == 10248);
            context.Log = Console.Out; 
            foreach(var r in product)

You can print the generated SQL by putting one line of code just before data gets loaded. In this scenario put following line of code anywhere but before the foreach statement.


You will get the generated SQL query in console as follows: clip_image001

You can set or get log of the DataContext in a TextWriter. If required you can save them on a file system etc.

Happy Coding.

3 responses to “How to view the generated SQL Query of LINQ”

  1. […] How to view the generated SQL Query of LINQ. […]

  2. […] How to view the generated SQL Query of LINQ (Dhananjay Kumar) […]

  3. ((Objectquery) query).totracestring();
    Get query string.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at