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.
Now we have already have table to its time to create a Linq-To-SQL dbml file.
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.
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.
For this post I am going to use same table like following. A customer table with two columns CustomerId and CustomerName.
Now we have already have table to its time to create a Linq-To-SQL dbml file.
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; 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.
That’s it. Hope you like it. Stay tuned for more.
0 comments:
Post a Comment
Your feedback is very important to me. Please provide your feedback via putting comments.