Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Log your LINQ query

4.93/5 (4 votes)
1 Dec 2011CPOL 17.6K  
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 operation) don't have an idea what query gets fired to database out of LINQ query.

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

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

C#
//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 gets fired on my database:

Image 1
 

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)