Monday, December 24, 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.

...
...

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.

Read more: DotNetJalps
QR: Inline image 1

Posted via email from Jasper-Net