Wednesday, June 26, 2013

RETRIEVING DATA FOR A PARTICULAR RELATIONSHIP

We have faced a situation where the entity was having a relationship but the relationship was not visible in the form. For example, a contact was having a category related. But in the form while creating a category for a contact there were no option for the user to select the contact for the category.
We were creating the record using the plugin and then associating the category to the contact using the AssociateRequest. Please find that blog here.


Before creating a category under a contact we wanted to check whether the same category is already associated with the contact for restricting the duplicates. This was done using the RelatedEntityCollection.

Below is the code snippet for the same.

QueryExpression query = new QueryExpression();
query.EntityName = "new_accountindustry";
query.ColumnSet = new ColumnSet("new_industry", "new_name");

Relationship relationship = new Relationship();

relationship.SchemaName = relationshipName;
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

relatedEntity.Add(relationship, query);
RetrieveRequest request = new RetrieveRequest();

request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet("fullname");

request.Target = new EntityReference
{

Id = contactId,
LogicalName = "contact"
};
RetrieveResponse response = (RetrieveResponse)orgService.Execute(request);

RelatedEntityCollection relatedEntityCollection = response.Entity.RelatedEntities;

relatedEntityCollection contains all the categories associated with the contactId passed as the parameter.
From the relatedEntityCollection if we have to get the data in EntityCollection we can use the following line of code.
     
EntityCollection entityCollection = (EntityCollection)relatedEntityCollection.Values.ElementAt(0);


Now we have the entityCollection handy with all the data available. Now I assume you know how to get the data from the entityCollection.


No comments:

Configuration for CRM Plugins

CRM plugins are always great feature where we can automate many functionality which we cannot automate from user interface. But almost eve...