Tip #217: Bad Id, bad

Following my anal retentive attention to the tightness of LINQ code and SQL it generates, I decided to refactor an old piece of code that extracted identifiers of the accounts matching certain criteria. Being very smug with all the newly acquired knowledge, I quickly produced an equivalent of:

var activeAccounts = crm.AccountSet
   .Where(a => a.Name.StartsWith("Bar"))
   .Select (a => a.Id);
           
foreach (var id in activeAccounts)
{
   Console.WriteLine("{0}", id);
}

To my horror, this code generated an equivalent of “select *” SQL statement (ok, it listed the columns explicitly but it listed all columns), neutralizing all my efforts. Explicit column name, on the other hand, generated mean and lean SQL:

var activeAccounts = crm.AccountSet
   .Where(a => a.Name.StartsWith("Bar"))
   .Select (a => a.AccountId);

object.Id is a very handy abstraction, but when it comes to LINQ, it’s a leaky one.

Leave a Reply

Your email address will not be published. Required fields are marked *