Where I can find SQL generated by Linq-To-SQL

Yesterday I have written a blog post about Where I can find SQL Generated by Entity Framework? and same day I got request from one of the our reader Ramesh that how I can find SQL generated by Linq-To-SQL?. I thought its a good idea to write a blog post to share amongst all who need this instead of reply in comments.  In this post I am going to explain how we can get SQL generated by Linq-To-SQL.

For this post I am going to use same table like following. A customer table with two columns CustomerId and CustomerName.

How to get SQL staement generated by Linq-To-SQL

Now we have already have table to its time to create a Linq-To-SQL dbml file.

How to find SQL Statement from linq-to-sql

Now once our dbml file is ready it’s time to import Customer Table from Server Explorer.


Now we are ready with Linq-To-SQL dbml file and its time to write some code. I am going write same query I have written for previous post where I can find all the customer name. Here I have used datacontext GetCommand method to get command from the dbml class and then used CommandText property to find SQL statement generated by our Linq-To-SQL query. Following is the code for that.

using System;
using System.Linq;
using System.Data;

namespace LinqToSQL
    class Program
        static void Main(string[] args)
            using (CustomerDataContext customerContext = new CustomerDataContext())
                var customerNames = from c in customerContext.Customers
                                    select c.CustomerName;
                string sql = customerContext.GetCommand(customerNames).CommandText;


Now let’s run this console application to see SQL generated by Linq-To-SQL query and following is the output as expected.


That’s it. Hope you like it. Stay tuned for more.

Shout it

kick it on DotNetKicks.com


Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio