Friday, December 21, 2012

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


Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
About Me
My Photo

Full Stack Developer, Blogger, Microsoft Mvp, Mentor, Lifelong learner, 12+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC/Core, C#, Angular,Vue.js and node.js
Subscribe to my blog


My You tube channel- Please Subscribe
Youtube Video Playlist
My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews