Create N:N Association, if not already present.
//Code follows
public void associateWithCheck(){
EntityCollection recordCollection = RetrieveMultiple_Attribute(entityLogicalName, new ColumnSet(entityField), entityField, sourceDataFields[0], client);
EntityCollection relatedRecordCollection = CrmHelper.RetrieveMultiple_Attribute(relatedEntityLogicalName, new ColumnSet(relatedEntityField), relatedEntityField, sourceDataFields[1], client);
if (recordCollection.Entities.Count > 1 || relatedRecordCollection.Entities.Count > 1)
{
// If you have more than one corresponding record in CRM do something
Console.WriteLine("More than 1 match for {0} - {1} please update CRM Data/Data Imported.", entityLogicalName, compareValue);
}
// Add to the update list - Match found
else if (recordCollection.Entities.Count == 1 && relatedRecordCollection.Entities.Count == 1)
{
Entity record = recordCollection.Entities[0];
Entity relatedRecord = relatedRecordCollection.Entities[0];
bool areEntitiesAlreadyAssociated = CrmHelper.RelationshipExists(relationshipName, record.Id, entityLogicalName, relatedRecord.Id, relatedEntityLogicalName,client);
if (!areEntitiesAlreadyAssociated)
{
// entitiesToUpdate.Entities.Add(recordForUpdate);
AssociateRequest associateRequest = new AssociateRequest
{
Target = new EntityReference(entityLogicalName, record.Id),
RelatedEntities = new EntityReferenceCollection
{
new EntityReference(relatedEntityLogicalName, relatedRecord.Id)
},
Relationship = new Relationship(relationshipName)
};
associateRequestWithResults.Requests.Add(associateRequest);
Console.WriteLine(entityLogicalName + " " + sourceDataFields[0] + relatedEntityLogicalName + " " + sourceDataFields[1] + "added to association list");
}
else {
Console.WriteLine(entityLogicalName + " " + sourceDataFields[0] + relatedEntityLogicalName + " " + sourceDataFields[1] + "already related");
}
}
}
No comments:
Post a Comment