Skip to content

How to know if LINQ is working efficiently with SQL?

Updated: at 02:12 PM

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();
}</pre>

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.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects