Hi All,
Recently while going through OrganizationService SDK Doc, I came across RelatedEntities concept where we can create Parent and Child records in one operation.
So I wanted to check this in my Pre-Operation plugin to see if it works. Requirement is to Create one Contact and 3 tasks when Account is created. I wrote below C# and registered plugin step on Create - Pre Operation stage. But none of the child records are getting created.
if (entity.LogicalName == "account")
{
// An accountnumber attribute should not already exist because
// it is system generated.
if (entity.Attributes.Contains("accountnumber") == false)
{
// Create a new accountnumber attribute, set its value, and add
// the attribute to the entity's attribute collection.
Random rndgen = new Random();
entity.Attributes.Add("accountnumber", rndgen.Next().ToString());
// Create Primary contact
var primaryContact = new Entity("contact");
primaryContact["firstname"] = "John";
primaryContact["lastname"] = "Smith";
// Add the contact to an EntityCollection
EntityCollection primaryContactCollection = new EntityCollection();
primaryContactCollection.Entities.Add(primaryContact);
// Set the value to the relationship
entity.RelatedEntities[new Relationship("account_primary_contact")] = primaryContactCollection;
// Add related tasks to create
var taskList = new List() {
new Entity("task") { ["subject"] = "Task 1" },
new Entity("task") { ["subject"] = "Task 2" },
new Entity("task") { ["subject"] = "Task 3" }
};
// Add the tasks to an EntityCollection
EntityCollection tasks = new EntityCollection(taskList);
// Set the value to the relationship
entity.RelatedEntities[new Relationship("Account_Tasks")] = tasks;
}
else
{
// Throw an error, because account numbers must be system generated.
// Throwing an InvalidPluginExecutionException will cause the error message
// to be displayed in a dialog of the Web application.
throw new InvalidPluginExecutionException("The account number can only be set by the system.");
}
}
I can achieve this with Post Operation plugin but wanted to reduce service calls to CRM Dynamics.
Please help me to understand why this is not creating any records. I don't get any error, it seems CRM system is ignoring child record code.
FYI - Account number is getting auto populated when I create New Account.