Platinum Partner
dotnet,linq,tips and tricks,.net & windows,c-sharp

How to Log Your LINQ Query

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}