When you query an entity you can link another entity to it. You might want to do this to:

  • add additional conditions to your query with pertain to a related entity
  • return columns from two entities within only one query (which is more efficient)

Here's a scenario:

You have a Product lookup on the Lead entity titled 'Product of Interest' and the Product entity has an option set called 'Product Type'. A query could therefore be to retrieve all Leads that have a Product of Interest where the Product has a 'Product Type' of 'Equipment'.

In C#, your QueryExpression would utilise a LinkEntity and read as follows:

var q = new QueryExpression { EntityName = "lead", ColumnSet = new ColumnSet(false) };
q.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);

var link = new LinkEntity
{
    LinkFromEntityName = "lead",
    LinkFromAttributeName = "new_productofinterest",
    LinkToEntityName = "product",
    LinkToAttributeName = "productid",
    JoinOperator = JoinOperator.Inner,
    EntityAlias = "Product",
    Columns = new ColumnSet(new string[] { "price" })
};

link.LinkCriteria.AddCondition("producttype", ConditionOperator.Equal, 550000001); // Equipment

q.LinkEntities.Add(link);

var results = service.RetrieveMultiple(q);

The query above retrieves all active Leads in CRM and links their Product of Interest, returning no columns from the Lead and the 'Price' column from the Product.

When retrieving the linked Product's 'Price' from a returned Lead, you might expect to be able to use GetAttributeValue, but unfortunately you can't. You must first use GetAttributeValue, then cast the object's Value property to Money, and then retrieve the Money's Value property... phew.

Here's the final code to retrieve a linked entity's Money value:

var firstLead = results.Entities.FirstOrDefault();
var price = ((Money)firstLead.GetAttributeValue<AliasedValue>("Product.price").Value).Value;

Note that the attribute you're retrieving from the Lead is "Product.price" not just "price". This is because LinkEntity attributes are prefixed with the EntityAlias property of the LinkEntity object passed to the QueryExpression (see the first code block above).