Search code examples
dynamics-crm-2011dynamics-crm

What is the Best Practice to update multiple fields in a Plugin


I have a plugin registered in Post operation that needs to update multiple fields in CRM using data from an XML file. Currently I am using the following code:

                    if (node["node1"] != null)
                    {
                            var sId = sElement.GetElementsByTagName("pId")[0].InnerText;
                            Guid sGUID = new Guid(sId);
                            sEntity["Attrib1"] = sGUID;
                            service.Update(sEntity);
                    }

                    if (node["node2"] != null)
                    {
                            var sMax = sElement.GetElementsByTagName("pMax")[0].InnerText;
                            sEntity["Attrib2"] = sMax;
                            service.Update(sEntity);
                    }

                    if (node["node3"] != null)
                    {
                            var sMin = sElement.GetElementsByTagName("pMin")[0].InnerText;
                            sEntity["Attrib3"] = sMin;
                            service.Update(sEntity);
                    }

So I am calling the service.Update each time I need to update and in the above case 3 times.

Is there a better way to accomplish what I am trying to do and call the service.Update only one time?


Solution

  • You can just do a single update in the end (eventually you can add a check in case none of the fields changed, to avoid a useless update):

      if (node["node1"] != null)
                        {
                                var sId = sElement.GetElementsByTagName("pId")[0].InnerText;
                                Guid sGUID = new Guid(sId);
                                sEntity["Attrib1"] = sGUID;
                        }
    
                        if (node["node2"] != null)
                        {
                                var sMax = sElement.GetElementsByTagName("pMax")[0].InnerText;
                                sEntity["Attrib2"] = sMax;
                        }
    
                        if (node["node3"] != null)
                        {
                                var sMin = sElement.GetElementsByTagName("pMin")[0].InnerText;
                                sEntity["Attrib3"] = sMin;
                        }
    service.Update(sEntity);