Thursday, June 12, 2014

Creating Related Entities using Late Bound OrganizationService with CRM2011 and CRM2013

Scenario
I have a Statement Entity and Create it. Then I want to add a child record, into StatementFacility.
This is not just a matter of assigning a foreign key based on the primary key; as usual with the SDK, you must perform some acrobatics. See the highlighted sections.

//CREATE THE PRIMARY ENTITY

Entity xrmse = new Entity("fcbt_statement");
xrmse.Attributes.Add("fcbt_prepareddate", sr.PreparedDate); //added
xrmse.Attributes.Add("fcbt_begindate", sr.BeginDate);
xrmse.Attributes.Add("fcbt_statementnumber", sr.StatementNumber);
xrmse.Attributes.Add("fcbt_ispaperless", sr.IsPaperless ?? false);
xrmse.Attributes.Add("fcbt_sharepointpermalinkurl", sr.SharepointPermalinkUrl);
xrmse.Attributes.Add("fcbt_xmlfiledate", sr.XmlFileDate);
xrmse.Attributes.Add("fcbt_xmlfilename", sr.XMLFileName);
statementGuid = myproxy.Create(xrmse);

// YOU MUST RETRIEVE IT AGAIN TO LINK THE RELATIONSHIP!
Entity statementEntity = myproxy.Retrieve("fcbt_statement", statementGuid, new ColumnSet(false));

// NOW CREATE THE CHILD ENTITY
    Entity xrmsfe = new Entity("fcbt_statementfacility");
    xrmsfe.Attributes.Add("fcbt_statement", statementEntity.ToEntityReference());
    xrmsfe.Attributes.Add("fcbt_facilitypid", srf.FacilityPid);
    xrmsfe.Attributes.Add("fcbt_facilitycontrolnumber", srf.FacilityControlNumber);

    Guid statementFacilityGuid = myproxy.Create(xrmsfe);

CREDIT GOES TO PATTY CAKES FOR THIS