.netsaveassociationsdynamics-crmentityreference

CRM 2015 SDK OrganizationService.Associate: If 1 in collections errors, do others still associate or all rollback?


In CRM 2015 SDK when you are using OrgService.Associate (wrapped in try/catch) to associate an EntityReferenceCollection to an Entity, if any one of the EntityReferences fails, does the entire ERC fail at that point? Or say there were 10 ERs in the ERC and the 7th one failed, do the first 6 succeed and then the subsequent 4 are not processed? Or do all 10 in ERC get processed and associate except just that #7 that failed?

Does this make sense?


Solution

  • The Associate message is processed in a single transaction, so if any of the related entities fails the entire transaction is rolled back.

    You can easily test it executing the following code:

    EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
    relatedEntities.Add(new EntityReference("account", new Guid("A88C66DD-0B29-E811-8126-5065F38AEA61"))); // Existing account #1
    relatedEntities.Add(new EntityReference("account", Guid.NewGuid())); // Non-existing account
    relatedEntities.Add(new EntityReference("account", new Guid("BA647CEA-0B29-E811-8126-5065F38AEA61"))); // Existing account #3
    
    service.Associate("contact", new Guid("0A3B1F8B-77F0-E711-811F-5065F38B06F1"), new Relationship("account_primary_contact"), relatedEntities);
    

    This will end up in a FaultException being thrown:

    System.ServiceModel.FaultException`1 occurred HResult=0x80131501
    Message=account With Id = 50a65bfc-1ed3-49de-b910-adef17febe3b Does Not Exist Source=mscorlib StackTrace: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Microsoft.Xrm.Sdk.IOrganizationService.Associate(String entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)

    And you will be able to check that no associations were created for account #1 and #3.