Monday, July 19, 2010

Entity Framework: How to log generated SQL in ASP.NET

If you want to log/view the generated T-SQL from your Entity Framework context instances to the output window in Visual Studio create a TextWriter derivation and use it like so:

using (MyEntityContext db = new MyEntityContext())
{
  db.Log = new OutputDebugWriter();
  ...
}

class OutputDebugWriter : 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; }
   }
}

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...