Trace LINQ to SQL Queries

By Fons Sonnemans, 4-12-2007

ASP.NET Tracing is a powerful mechanism. LINQ to SQL doesn't support it out of the box. The DataContext class however has a Log property which can be set to a TextWriter object. This TextWriter object writes all SQL queries which are executed.

I have created a small class which derives from TextWriter to write all SQL queries to the System.Diagnostics.Trace class. I found out that I only had to override the WriteLine(string) and Write(string) methods.

The easiest way to assign a new TextToTraceWriter to the Log property of the DataContext object is by implementing the partial OnCreated() method in a partial class. See the following example in which also the Trace Category is set.

I changed my web.config and added a system.diagnostics section. In this section I added the WebPageTraceListener tracelistner. In my project the LINQ to SQL Classes are placed in the App_Code folder and not in a referenced ClassLibrary. To enable diagnostics tracing for my web project I have to add the compileOption="/d:TRACE" to the c# compiler in the system.compilers section of the web.config. For ClassLibraries you only have to check the 'Define TRACE constant' Build Option in the Project Properties.

When you add tracing to the page you will see all LINQ queries in the Trace. This will give you a better understanding in what is going on behind the LINQ curtains

The TextToTraceWriter class can also be used for Windows Forms or Console Applications in which LINQ is used.

Click here to download a copy of the above sample in order to try it out on your own machine.

Tags: CSharp

Leave a Comment

Leave a Comment
Name
Comment
8 + 5 =

0 Comments

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.