How to log DLinq’s Sql commands

There was a question on MS’ forum about how to log the DLinq’s sql commands. Well, actually DataContext’s sql commands. Here is the solution, it is easy:


StringBuilder sb = new StringBuilder();   // create a StringBuilder instance to store output
TextWriter tw = new StringWriter(sb);     // create a StringWriter that will write into StringBuilder above
db.Log = tw;                              // attach it to DataContext
Console.WriteLine(sb.ToString());         // output the result


The trick is to use DataContext.Log property (db represents DataContext instance in this example) to attach a valid TextWritter derived instance. And voila – no more black box. Of course, output will be empty unless there is a sql command issued either by doing query or persistence.

Leave a Reply