Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Track Queries on a Linq-to-sql DataContext

In the herding code podcast 14 someone mentions that stackoverflow displayed the queries that were executed during a request at the bottom of the page.

It sounds like an excellent idea to me. Every time a page loads I want to know what sql statements are executed and also a count of the total number of DB round trips. Does anyone have a neat solution to this problem?

What do you think is an acceptable number of queries? I was thinking that during development I might have my application throw an exception if more than 30 queries are required to render a page.

EDIT: I think I must not have explained my question clearly. During a HTTP request a web application might execute a dozen or more sql statements. I want to have those statements appended to the bottom of the page, along with a count of the number of statements.

HERE IS MY SOLUTION:

I created a TextWriter class that the DataContext can write to:

public class Logger : StreamWriter
    {
        public string Buffer { get; private set; }
        public int QueryCounter { get; private set; }

        public Logger() : base(new MemoryStream())
        {}

        public override void Write(string value)
        {
            Buffer += value + "<br/><br/>";
            if (!value.StartsWith("--")) QueryCounter++;
        }

        public override void WriteLine(string value)
        {
            Buffer += value + "<br/><br/>";
            if (!value.StartsWith("--")) QueryCounter++;
        }
    }

In the DataContext's constructor I setup the logger:

public HeraldDBDataContext()
        : base(ConfigurationManager.ConnectionStrings["Herald"].ConnectionString, mappingSource)
    {
        Log = new Logger();
    }

Finally, I use the Application_OnEndRequest event to add the results to the bottom of the page:

protected void Application_OnEndRequest(Object sender, EventArgs e)
    {
        Logger logger = DataContextFactory.Context.Log as Logger;
        Response.Write("Query count : " + logger.QueryCounter);
        Response.Write("<br/><br/>");
        Response.Write(logger.Buffer);
    }
like image 887
liammclennan Avatar asked Aug 27 '08 01:08

liammclennan


2 Answers

If you put .ToString() to a var query variable you get the sql. You can laso use this in Debug en VS2008. Debug Visualizer

ex:

var query = from p in db.Table
            select p;

MessageBox.SHow(query.ToString());
like image 157
Jedi Master Spooky Avatar answered Sep 21 '22 05:09

Jedi Master Spooky


System.IO.StreamWriter httpResponseStreamWriter = 
new StreamWriter(HttpContext.Current.Response.OutputStream);

dataContext.Log = httpResponseStreamWriter;

Stick that in your page and you'll get the SQL dumped out on the page. Obviously, I'd wrap that in a little method that you can enable/disable.

like image 24
FlySwat Avatar answered Sep 21 '22 05:09

FlySwat