Clone CRM Record CRM 2011

Many times while working on CRM 2011, we come across a situation to clone the quote or invoice records. Immediately we will start writing the code for getting the record and creating the same record again and continue the same for child records i.e. quote products or invoice lines etc…

Even I have came across the same situation then my team lead and me wrote a generic method for cloning CRM records.

Here is that method…

        #regionCloneRecord

                ///


                /// Method to Clone CRM Record.
                ///


                /// Parent entity name ex: invoice
                /// Parent primary attribute name ex:invoiceid
                /// Guid of the parent record
                /// Selected attributes to copy from one record to another. If you wanna copy all records,
                /// just send the parameter as null then the considers all attributes.

                /// Attributes to remove from parent entity.

                /// Child entity name ex: invoicedetail
                /// Child primary attriubute name ex: invoicedetailid
                /// Attributes to remove from child entity
               /// Guid of the parent record
                public GuidCloneCRMRecord(string strEntityName, string strParentEntityPKAttrName, Guid guidParent, string[] strAttributesToFetch, string[] strArrRemoveParentAttributes, string strChildEntity, stringstrChildEntityFKAttrName, string[] strArrRemoveChildCols)
                {
                    Microsoft.Xrm.Sdk.Entity parentEntity = new Microsoft.Xrm.Sdk.Entity(strEntityName);
                    if (strAttributesToFetch == null)
                    {
                        parentEntity = _crmService.Retrieve(parentEntity.LogicalName, guidParent, new ColumnSet(true));
                    }
                    else
                    {
                        parentEntity = _crmService.Retrieve(parentEntity.LogicalName, guidParent, new ColumnSet(strAttributesToFetch));
                    }
                    if (strArrRemoveParentAttributes == null) strArrRemoveParentAttributes = new string[] { “” };
                    RemoveEntityAttributes(ref parentEntity, strArrRemoveParentAttributes);
                    /*
                        Below line is must otherwise, “Create” will result in:
                        FaultException’1 was unhandled.
                        Cannot insert duplicate key.
                    */
                    parentEntity.Id = Guid.NewGuid();
                    Guid newEntityRecordId = _crmService.Create(parentEntity);
                    //
                    if (string.IsNullOrEmpty(strChildEntity) == false)
                    {
                        #region Retrieve all the Child Entity Record details from the original Parent Entity Record.
                                ConditionExpression expression = new ConditionExpression();
                                expression.AttributeName = strChildEntityFKAttrName;
                                expression.Operator = ConditionOperator.Equal;
                                expression.Values.Add(guidParent);
                                FilterExpression expression2 = new FilterExpression();
                                expression2.FilterOperator = LogicalOperator.And;
                                expression2.Conditions.Add(expression);
                                QueryExpression query = newQueryExpression();
                                query.EntityName = strChildEntity;
                                query.ColumnSet = new ColumnSet(true);
                                query.Criteria = expression2;

                        #endregion

                        EntityCollection allChildEntityRecords = _crmService.RetrieveMultiple

(query);

                        if (allChildEntityRecords != null)
                        {
                            //One by one create Child Entity records in the Parent Entity.sales order detail record and set its FK Id to the Cloned Parent Entity Id
                            //and PK Id to new GUID.
                            #region Create Child Entity Records under the Parent Entity.
                                    Microsoft.Xrm.Sdk.EntityclonedChildEntity = null;
                                    if(strArrRemoveChildCols == null) strArrRemoveChildCols = new string[] { “”};
                                    Guid newChildEntityRecordId = Guid.Empty;
                                    foreach (Microsoft.Xrm.Sdk.EntitychildEntity in allChildEntityRecords.Entities)
                                    {
                                        clonedChildEntity = newMicrosoft.Xrm.Sdk.Entity(strChildEntity);
                                        clonedChildEntity = _crmService.Retrieve(clonedChildEntity.LogicalName, childEntity.Id, new ColumnSet(true));
                                        EntityReference refParent = new EntityReference(parentEntity.LogicalName, parentEntity.Id);
                                        clonedChildEntity.Attributes[strChildEntityFKAttrName] = refParent;
                                        RemoveEntityAttributes(refclonedChildEntity, strArrRemoveChildCols);
                                        /*
                                            Below line is must otherwise, “Create” will

result in: FaultException’1 was unhandled. Cannot insert duplicate key.

                                        */
                                        clonedChildEntity.Id = Guid.NewGuid();
                                        newChildEntityRecordId = _crmService.Create(clonedChildEntity);
                                    }
                            #endregion
                        }
                    }
                    return parentEntity.Id;
                }
          
                 //Method to remove attributes from entity.
                private voidRemoveEntityAttributes(ref Microsoft.Xrm.Sdk.Entity inputEntity, string[] strArrRemoveCols)
                {
                    for (intintLoop = 0; intLoop < strArrRemoveCols.Length; intLoop++)
                    {
                        inputEntity.Attributes.Remove(strArrRemoveCols[intLoop]);
                    }
                }
        #endregion

 Happy Programming…. 🙂

 

3 thoughts on “Clone CRM Record CRM 2011

  1. Anonymous November 14, 2013 / 7:33 pm

    Your code wont work as it throw the following exception \”Entity Id must be the same as the value set in property bag\”

    Like

  2. Nandha S November 14, 2013 / 7:34 pm

    This comment has been removed by the author.

    Like

  3. Nandha S November 14, 2013 / 7:52 pm

    Adding this line just before creating the entity will help RemoveEntityAttributes(ref parentEntity, new string[] {strParentEntityPKAttrName});

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s