Dynamics CRM 2011 – Querying Data with QueryExpression

Roshan Mehta, 30 April 2012

Developers can utilize the power of the Microsoft Dynamics CRM 2011 SDK to build custom applications, plug-ins, and workflows which communicate with the CRM platform. Queries can be written to retrieve information from the CRM database in many different ways. In this blog, I will explain the use of the QueryExpression class and see how it can be used to write simple and complex queries.

QueryExpression is useful in scenarios where you want to return multiple entities that match a certain criteria. It lets you specify which fields you want to have returned (from the specified entity type or any related entity) as part of the query result in order to improve performance. Developers can also control the order in which records are returned.

To illustrate the power of QueryExpression, let’s take a look at a few examples:

Example 1 – Simple query with two conditions for a single entity

Scenario: Retrieve the First Name, Last Name, and Email Address for Contacts that have the Job Title field set and live in Auckland city

Dynamics CRM 2011 Querying Data with QueryExpression

Example 2 – Complex query with multiple conditions across two related entities

Scenario: Retrieve the First Name, Last Name, and Email Address for Contacts that are “Sales Managers” and the Parent Customer is based in Auckland or Wellington city

Dynamics CRM 2011 Querying Data with QueryExpression

Example 3 – Simple query with OrderExpression

Scenario: Retrieve all Accounts in the system and order by the date created (most recent first) 

Dynamics CRM 2011 Querying Data with QueryExpression

Those are just a few examples of how you can write queries using QueryExpression. Developers can use any combination of LinkEntity, ConditionExpression and OrderExpression to write complex queries.