Skip to content

LOG LINQ 2 SQL query execution to console/debug window

Wow, I just learnt a valuable trick in LINQ 2 SQL.

Set your DB Data Context “Log” property to “Console.Out” and once a query has been executed by LINQ 2 SQL, the query executed is outputted to console! This is great, but I straight away would want this sending to a debug window or if you are after further flexibility, you can output to a file, memory or multiple output writers with the below code:

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; }
   }
}

To use it then simply:

#IF DEBUG
myDataContext.Log = new DebugTextWriter();
#endif

^^ I personally use the “#IF DEBUG” line that way this only occurs in debug mode, but it is up to you.

Major thanks to DamienG over at his blog!

VN:F [1.9.1_1087]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.1_1087]
Rating: 0 (from 0 votes)
Bookmark and Share
kick it on DotNetKicks.com
Shout it

NOW, FOR A WORD FROM OUR SPONSORS

One Comment

  1. Thank you for that short version!
    I saw a lot of other implementations with at least 100 lines of code!

    I would decorate the DebugWriter with
    [Conditional("DEBUG")]
    instead of using
    #IF DEBUG

    THANKS
    .peter.gfader.

    VA:F [1.9.1_1087]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.1_1087]
    Rating: 0 (from 0 votes)
    Posted on 22-Oct-09 at 2:54 pm | Permalink

One Trackback/Pingback

  1. DotNetShoutout on 05-Feb-09 at 10:23 am

    Log LINQ 2 SQL query execution to console/debug window « {Programming} & Life…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

    VA:F [1.9.1_1087]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.1_1087]
    Rating: 0 (from 0 votes)

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...