Dynamics CRM 2011 – Querying Data with QueryByAttribute

Roshan Mehta, 02 May 2012

In my previous post, I showed you how to write simple and complex queries using the QueryExpression class. Another way in which developers can query CRM records is through QueryByAttribute, which allows you to search for records where a specific set of fields matches a specific set of values. Like QueryExpression, it can be used with the RetrieveMultiple method to return a collection of matching records.

One thing to note about QueryByAttribute is that it can only make value comparisons using the “equals” operator. Unlike QueryExpression, this approach does not require the use of a ConditionOperator since we can only use value equality.

Example – Find all active Accounts that are based in the city of Auckland. We only want to return the name and account number for all Accounts matching this condition.
Dynamics CRM 2011 Querying Data with QueryByAttribute

QueryByAttribute supports the OrderExpression to return data in a specific order. However, we are unable to query data by columns from related entities using LinkEntity. This approach is only available when using QueryExpression.

If we were to build the same query using QueryExpression, it would look something like this:

Dynamics CRM 2011 Querying Data with QueryByAttribute

Although both queries achieve the same result, the second query looks a little more complex than the first.