Over a million developers have joined DZone.

Log your LINQ query


Most of the beginner developer who are using LINQ to SQL as there back-end to talk with the database (i.e to perform the database CRUD operation), don't have idea what the query get fire to database out of LINQ query.

Lastly I asked to log the query that fire to database out of my LINQ query. So as solution I found one make use of SQL Server Profiler to check fire query. But with the profiler I can not able to log the queries.

I fond one solution is to make use of Log property of DataContext object. Log property allow me to log the queries in the file. Consider the below code

//created temp file 
(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 }
                new { CityID = d.CityId, StateID = d.StateId, 
                      CountryID = d.CountryId, Id = d.DistributorId }
              select c;

    List<customer> custList = cust.ToList();

So once the code get executed it's time to check the temp file. As I opened up the file I found following query get fired on my database.

It's fun to find the query get fire to database and you get to know if there is any problem in the LINQ query you wrote.

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}