Advertisement
Advertisement


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


Question

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);
    }
2015/09/13
1
7
9/13/2015 6:22:25 PM


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.

2008/08/27

2008/09/16

From Linq in Action

Microsoft has a Query Visualizer tool that can be downloaded separetly from VS 2008. it is at http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx

2008/08/27