Get AliasedValue attributes with Early Bound

Sometimes we need to retrieve data from primary and related entity. Let us consider the following FetchXML to retrieve data of accounts and the related primary contact.

fecthXml

Each entity of the retrieved entity collection contains the attributes of the related entity in its attributes collection, where for each related attribute the:

The next image shows how to access the AliasedValue type attributes. To get any AliasedValue type attribute is required to get them from the base entity, even though, use early bound.

aliasedValue_contact

The AliasedValue class contains the next properties (as shown in the above picture):

  • AttributeLogicalName: contains the name of the attribute on which the select operation was performed;
  • EntityLogicalName: contains the name of the entity the attribute belongs to;
  • Value: contains the value returned by the query.

In order to use early bound with related entities I have developed the flowing extension method to the entity class:

public static T GetRelatedEntity<T>(this Entity entity) where T : Entity, new()
{
   T relatedEntity = new T();
// Get from entity all attribute AliasedValue type which EntityLogicalName is equal to RelatedEntity LogicalName
   entity.Attributes.Where(attr => attr.Value is AliasedValue
&& (attr.Value as AliasedValue).EntityLogicalName.Equals(relatedEntity.LogicalName))
.Select(attr => attr.Value as AliasedValue).ToList().ForEach(attr =>
      {
         relatedEntity.Attributes.Add(attr.AttributeLogicalName, attr.Value);
      });
   return relatedEntity;
}

With this extension method we are able to access the related entities using early bound as shown next, simplifying a lot the way to get attributes of related entities.

extension_method

Leave a comment