Monday, June 29, 2015

Merge records with automatic selection of all fields with data

When merging the records in GUI, you have the option of selecting the option which updates the master record with the values from the child record when the value is missing in the master record.

The below code does the same. If does a retrieve on the master and child record and then compares the columns from the child record with the master record and update the "UpdateContent" property of the merge request.

For merging custom entities, the first part of the code can be used and If we have a custom masterid created, the lookup value can be updated with the master record id and the child record can be inactivated/deleted.

public static bool MergeRecord(IOrganizationService _service, string entName, string srcId, string targetId)
            bool result = false;
            MergeRequest mreq = new MergeRequest();
            Guid targetRecordID = new Guid(targetId);
            Guid tobemergedRecordID = new Guid(srcId);
            Entity srcEntity = _service.Retrieve(entName, tobemergedRecordID, new ColumnSet(true));
            Entity tgtEntity = _service.Retrieve(entName, tobemergedRecordID, new ColumnSet(true));
            Entity updContent = new Entity(entName);
            foreach (KeyValuePair<String, Object> attr in srcEntity.Attributes)
                if (!tgtEntity.Attributes.Contains(attr.Key))

            mreq.Target = new EntityReference(entName, targetRecordID);  // Target Account ID , where other account will be mergered
            mreq.SubordinateId = tobemergedRecordID;
            mreq.PerformParentingChecks = false;
            mreq.UpdateContent = updContent;
                MergeResponse mresp = (MergeResponse)_service.Execute(mreq);
                result = true;
            catch (Exception ex)
                string message = ex.Message;
                LogMessage(message, true);
                result = false;

            return result;

No comments: