How to know if LINQ is working efficiently with SQL?

Recently, I recieved the following question on my blog regarding a post I made about using the aggregate function Count.  The question is as follows:

 does the LINQ implementation send a full query or just a count query? That can be a big waste, especially if this is called often?

One of the nice things about LINQ is you don’t have to guess.  By simply turning the Log property to true of the DBContext, you can see what LINQ is actually sending to the database.  below is some simple code that shows how to do this.

  protected void Page_Load(object sender, EventArgs e)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        StringWriter sw = new StringWriter();
        db.Log = sw;
        int cnt = (from tbl in db.tblAllTimes select tbl).Count();
        TextBoxResults.Text = sw.ToString();

    }

The results of running this are as follows:

  results

So, the answer is that is sending what seems to me to be the most efficient request it can.

I more mystery solved.

Thanks for reading.

About Peter Kellner

Follow me:


Comments

  1. Atleast in this i would differ from your answer as in teh select the query is mentioend as select count(*) from [value] but if it is count(1) it makes the most effective that with (*).

  2. It does most of the time.

Follow

Get every new post delivered to your Inbox

Join other followers: