When developing a LINQ to SQL data access layer, a common debugging task is to view the actual SQL statements developed by the LINQ to SQL runtime.  There are a variety of ways to do it, such as running a SQL trace or using the LINQ to SQL Debug Visualizer, but the one I find most practical and easy to use is to write the T-SQL directly to the Visual Studio output window. 

The LINQ To SQL team had the foresight to allow the capture of statements, which is simply done by attaching a class implementing System.IO.TextWriter to the .Log property of the DataContext.

A simple implementation of this is the following DebugTextWriter:

public class DebugTextWriter : System.IO.TextWriter
    public override void Write(char[] buffer, int index, int count)
        System.Diagnostics.Debug.Write(new String(buffer, index, count));

    public override void Write(string value)

    public override Encoding Encoding
        get { return System.Text.Encoding.Default; }

To use the DebugTextWriter and direct the output to the window, all that is needed is to instantiate a DebugTextWriter object and set it to the .Log property:

            MyDataContext dataContext = new MyDataContext();
            dataContext.Log = new DebugTextWriter();

The purpose of the #if DEBUG ( and ending #endif ) is to ensure that this code is only compiled into the debug version of the assembly.  It is not compiled when the Release configuration is enabled. 

Once this code has been put in place, executing any LINQ to SQL query will result in the actual T-SQL statements executed being written in the output window when you attached to the debugger:


I find that enabling this code at the start of a project makes it a breeze to look at the native T-SQL being sent to the database during all of my debugging sessions.

- Colin