I've often found it helpful to use ASP.NET's Page Trace to identify performance problems with my dynamic pages. However, database queries are frequently responsible for performance problems. Because of this, I began displaying SQL via the Page Trace. This let me see the SQL being executed to render a page. It also let me see how much time the SQL was taking to execute.
As I began toying with LINQ to SQL I found myself missing the ability to see the SQL being executed to render my pages. As it turns out, it's very easy to have LINQ output the SQL to Page Trace.
First you need to create a VERY simple class that implements the "System.IO.TextWriter" class. You can place this file in ~/App_Code/TraceTextWriter.cs
| using System; |
| using System.Web; |
| |
| public class TraceTextWriter : System.IO.TextWriter |
| { |
| public override System.Text.Encoding Encoding |
| { |
| get { throw new NotImplementedException(); } |
| } |
| |
| public override void WriteLine(string value) |
| { |
| HttpContext.Current.Trace.Write("LINQ", value); |
| base.WriteLine(value); |
| } |
| } |
Next you need to set the LINQ Log property to use an instance of this new TraceTextWriter class:
| TestDataContext db = new TestDataContext(); |
| TraceTextWriter traceWriter = new TraceTextWriter(); |
| db.Log = traceWriter; |
| |
| // Execute your LINQ queries here. |
Now set Trace to "true" inside your "aspx" page:
| <%@ Page Language="C#" AutoEventWireup="true" Trace="true" %> |
Piece of cake! Now load the page in a web browser and you will see details similar to the following:

Now you can easily see the SQL LINQ is generating to render your pages; you can also use this information to troubleshoot performance problems. When you are done troubleshooting, simply set Trace to "false" to disable this output.
Thanks to Matt Berseth for posting information that helped me get started on this.