Introduction:
In this Blog, we will see how to clone OOB/Custom Entities in Dataverse or MSCRM Environment.
Scenario:
Consider I have an Opportunity Entity Available, once the Opportunity is WON or LOST, we want to Clone that Opportunity with Exact Same Details.
Let's see how we can achieve this.
Note:
This Code is not only Restricted to OOB Entity, we can use this code in Custom Entity too
Implementation Steps:
You can write the below code in your Plugins.
Entity getOpprotuntiyRecord = (Entity)context.InputParameters["Target"];
Entity cloneRecord = service.Retrieve("opportunity", getOpprotuntiyRecord.Id, new ColumnSet(true));
cloneRecord.Attributes.Remove("opportunityid");
cloneRecord.Id = Guid.NewGuid();
Guid getCreatedOpportunity = service.Create(cloneRecord);
In the Above Code i mentioned as
opportunity --> Change it based on your Entity Logical Name
opportunityid --> Entity Logical Name Primary Unique id name
That's it
If Suppose you want to add some value to NAME Field while Cloning means you can write below code
Entity cloneRecord = service.Retrieve("opportunity", getOpprotuntiyRecord.Id, new ColumnSet(true));
cloneRecord.Attributes["name"] = cloneRecord.Attributes["name"].ToString() + " Renewal";
cloneRecord.Attributes.Remove("opportunityid");
cloneRecord.Id = Guid.NewGuid();
Guid getCreatedOpportunity = service.Create(cloneRecord);
You can Just Add the LOGICAL NAME while replacing.