.NET Zone is brought to you in partnership with:

I am Microsoft C# MVP July - 2012 My name is Pranay Rana. Currently, I'm working as senior software engineer in a mid-sized company (Ahmedabad). I have 5 years of the experience in web development with Asp.Net, C# and MS SQL server. For me, the definition of programming is: something that you do once and that gets used by multiple users for many years Pranay is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

How to Log Your LINQ Query

06.27.2012
| 4928 views |
  • submit to reddit
Most of the beginner developers who are using LINQ to SQL as their back-end to talk with the database (i.e to perform the database CRUD operations), don't understand which queries get sent to the database out of a LINQ query.

I can show you how to log the query that fires to the database out of my LINQ query. So as solution I found a tool that uses the SQL Server Profiler to check the query. But with the profiler I cannot log the queries.

I found one solution is to use the Log property of the DataContext object.  The Log property allows me to log the queries in a file. Consider the code below:
//created temp file
using
(System.IO.StreamWriter sw = new System.IO.StreamWriter(@"e:\tempdatacontext.log"))
{
    EmployeeDataContext edb = new EmployeeDataContext();
    //assigned streamwriter to the log property of datacontext
    edb.Log = sw;
    var cust = from c in edb.Customers
              join d in edb.Distributors on
                new { CityID = c.CityId, StateID = c.StateId,
                      CountryID = c.CountryId, Id = c.DistributorId }
                equals
                new { CityID = d.CityId, StateID = d.StateId,
                      CountryID = d.CountryId, Id = d.DistributorId }
              select c;
 
    List<customer> custList = cust.ToList();
}
So once the code gets executed it's time to check the temp file. As I opened up the file I found the following query getting fired into my database.


It's fun to see the queries as they get fired into the database and you get to know if there is any problem in the LINQ query you wrote.  Fun, and important!



Published at DZone with permission of Pranay Rana, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)