CRM 2011 – in plugins only select the fields you need and not ColumnSet(true)

usually when I am first developing some code in a plugin I will select all columns in the query

e.g.

account Account= (account)service.Retrieve(account.EntityLogicalName, id, new ColumnSet(true));

Once I know the code is working I will change this to pass only retrieve the fields I need because this makes the code run quicker and it’s basically just lazy to select all the columns

I usually pass in a list

List<string> fields = new List<string> { “name”, “accountnumber”, “creditlimit” };

and set that to the columns.

 

Today I had to do this to fix a puzzling problem I was having.  My CRM was acting a bit wierd, I got a few timeouts when just viewing a custom entity form.  I couldn’t understand this at all because there wasn’t loads of field on the entity and there also wasn’t a lot of records so there was no reason I could the SQL should be running slow.

On the custom entity I did have a workflow which checked if certain fields changed and if they did it would set some fields on another entity.

I also had a plugin which was kicked off on the update event and in this plugin it was retrieving all the custom entity fields and then doing an update.

What was happening is I somehow triggered a loop which the workflow ran and this kicked off the update plugin, my criteria on running the update plugin were always being hit and then I was saving the whole record.  This triggered the plugin.  I ended up with initially 200 workflows had been kicked off for my custom entity.

Even after I fixed the criteria to run only when certain fields had been changed my workflow was still firing a few times.

This was valid because the custom entity was correctly being updated by the plugin but because I had retrieved all the fields the workflow was being triggered, this was not correct because the fields the workflow was monitoring were not actually have any data changed.

So I modified my code to only select the fields I was going to check/change and after I had done this the workflow stopped getting triggered incorrectly and a bonus my code ran a lot quicker.

Perhaps there is a lesson here for me, get the code selecting the correct fields from the start and don’t be lazy with retrieving and writing all the fields of an entity.