Thursday, August 6, 2015

Create records with related records

Sometimes you will need to create a record with related records at the same time.
I used to create the related records before the parent record and then update them to set the reference of their parent. I wasn't satisfied by this method, so I searched on the Internet and there is a proper way to create related record.
It's pretty easy, I'll show you :)

Here is a example of the method using Late Bound Entities :
public void CreateRecord()
{
    Entity parentEntity = new Entity("new_parententity");
    parentEntity["new_name"] = "Parent Entity";
    
    // Create an collection of entity containing the associated records
    EntityCollection childEntityCollection = new EntityCollection { EntityName = "new_childentity" };
    
    // Add 3 children to the parent record
    for (int i = 0; i < 3; i++)
    {
        Entity childEntity = new Entity("new_childentity");
        childEntity["new_name"] = string.Format("Child Entity {0}", i + 1);
        childEntityCollection.Entities.Add(childEntity);
    }
    
    parentEntity.RelatedEntities.Add(new Relationship("new_parententity_childrenentities"), childEntityCollection);
    
    // Create the parent record and the related records
    // OrganizationService is an instance of the IOrganizationService interface
    OrganizationService.Create(parentEntity);
}

Source : TechNet