Retrieve related entities of each, using RetrieveMultipleRequest

Milton picture Milton · Dec 4, 2012 · Viewed 9.3k times · Source

I'm trying to retrieve a list of entities from CRM, but I'd like to get each one with the related entities. So far, I've the following code:

FilterExpression filterExpression = new FilterExpression();
ConditionExpression condition = new ConditionExpression(Constants.ModifiedOnAttribute, ConditionOperator.GreaterEqual, lastSync);
filterExpression.AddCondition(condition);

QueryExpression query = new QueryExpression()
{
     EntityName = entityName,
     ColumnSet = new ColumnSet(attributesMetadata.Select(att => att.Name).ToArray<string>()),
     Criteria = filterExpression,
     Distinct = false,
     NoLock = true
};

RetrieveMultipleRequest multipleRequest = new RetrieveMultipleRequest();
multipleRequest.Query = queryExpression;

RetrieveMultipleResponse response = (RetrieveMultipleResponse)proxy.Execute(multipleRequest);

In the variable response, I can see the EntityCollection attribute, but inside, Related entities always come empty.

Related entities count is 0

I'd like to know if it is possible to retrieve the set of a given entities, with the related entities, using RetrieveMultipleRequest, rather than go one by one using RetrieveRequest.

Answer

SergeyS picture SergeyS · Dec 4, 2012

One approach to retreive related entities data - adding LinkEntities to your query. Example below will make you an idea how to make this:

LinkEntity linkEntity = new LinkEntity("email", "new_emails", "activityid", "new_relatedemail", JoinOperator.Inner);
linkEntity.Columns.AddColumn("versionnumber");
linkEntity.Columns.AddColumn("new_emailsid");
linkEntity.EntityAlias = "related";

query = new QueryExpression("email");
query.ColumnSet.AddColumn("activityid");
query.ColumnSet.AddColumn("versionnumber");
query.Criteria.AddCondition("modifiedon", ConditionOperator.NotNull);
query.LinkEntities.Add(linkEntity);

And then you can access attributes from related entities using EntityAlias you specified above:

foreach (Entity entity in entities.Entities)
{
    if ((long)(entity["related.versionnumber"] as AliasedValue).Value > 0)
    {
        stop = false;
    }
}