Image you have an entity record and you would like to retrieve properties of some related entities. You can accomplish this in C# by using the LinkedEntities property of a QueryExpression.
Let’s take the following example, we have a ‘zen_career’ record which is linked to a contact record which is in turn linked to an owner record.
We would like to retrieve the contact’s firstname and his owner’s name starting from the zen_career. Example code using RelatedEntities:
[code language=”csharp” wraplines=”false”]
Guid careerId = Guid.Parse("7F1A0C5A-C66D-E611-80CA-0050568E035D");
QueryExpression careerExpression = new QueryExpression("zen_career");
careerExpression.TopCount = 1;
careerExpression.NoLock = true;
careerExpression.Criteria.AddCondition("zen_careerid", ConditionOperator.Equal, careerId);
LinkEntity careerContact = new LinkEntity("zen_career", "contact", "zen_contactid", "contactid", JoinOperator.Inner)
{
Columns = new ColumnSet("firstname"),
EntityAlias = "contact",
};
LinkEntity contactOwner = new LinkEntity("contact", "owner", "ownerid", "ownerid", JoinOperator.Inner)
{
Columns = new ColumnSet("name"),
EntityAlias = "owner",
};
careerContact.LinkEntities.Add(contactOwner);
careerExpression.LinkEntities.Add(careerContact);
EntityCollection careerContactResult = _orgService.RetrieveMultiple(careerExpression);
Entity contact = careerContactResult.Entities.FirstOrDefault();
if (contact != null)
{
string firstName = contact.GetAliasedValue("contact.firstname");
string owner = contact.GetAliasedValue("owner.name");
}
[/code]
We use an extension method GetAttributeValue, to optain the value of an AliasedValue. Source code:
[code language=”csharp” wraplines=”false”]
public static T GetAliasedValue(this Entity entity, string attribute, T def = default(T))
{
AliasedValue value = entity.GetAttributeValue<AliasedValue>(attribute);
if (value == null)
return def;
object result = value.Value;
if (result == null)
return def;
return (T)result;
}
[/code]