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.

Linq-To-SQLClassGeneration

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;

                Console.WriteLine(sql);
            }
        }
    }
}

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

OutPutSQL

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

Shout it

kick it on DotNetKicks.com
Share:

0 comments:

Post a Comment

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

Search This Blog
Loading...
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews