How to Log Your LINQ Query
Join the DZone community and get the full member experience.
Join For FreeMost 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:
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!
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!
Database
Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments