How to get the TSQL Query from LINQ DataContext.SubmitChanges()

tsilb picture tsilb · Mar 12, 2009 · Viewed 19.5k times · Source

I'm using Linq to SQL. I have a DataContext against which I am .SubmitChanges()'ing. There is an error inserting the identity field, and I'd like to see the query it's using to insert this identity field.

I don't see the query itself within the quickwatch; where can I find it from within the debugger?

Answer

Portman picture Portman · Mar 12, 2009

Lots of people have been writing their own "DebugWriter" and attaching it like so:

// Add this class somewhere in your project...
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) {
       System.Diagnostics.Debug.Write(value);
   }

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

// Then attach it to the Log property of your DataContext...
myDataContext.Log = new DebugTextWriter()

This will output everything that Linq-to-Sql is doing into Visual Studio's debug window.