Subscribe to get your issue of Dynamics University
Breaking down the structure of the QueryExpression Class
So you are new to CRM development and you are just beginning to use Query Expressions. When we learn something new it is a common tendency to relate to something we know. While this can sometimes create inadvertent, mental roadblocks, it is nonetheless a common tendency. As I was learning how to use the QueryExpression class, I found that what got it to finally “gel” for me was equating the components to a standard SQL query.
Let’s consider the following SQL query:
Select name from FilteredAccount where address1_city=’Fargo’ or address1_city=’Buxton’
As you can see, all we are doing is getting a list of account names that are from Fargo or Buxton. Simple enough, right? Well, how does this equate to a QueryExpression?
Let’s review the components of using the QueryExpression class:
Essentially, this is our query. There are various properties we set when we instantiate the class such as:
- Entity: Specifies which type of entity will be retrieved.
- ColumnSet: Specifies the set of attributes (columns) to retrieve.
- Criteria: Specifies complex conditional and logical filter
As we build the other components listed below, they aggregately become our QueryExpression.
The ColumnSet identifies which fields we want returned when our query is actually ran.
The ConditionExpression allows us to filter the results of our query. For example, if I only want to return records that have a specific value, you would use the ConditionExpression to do it.
The FilterExpression allows you to take one or more condition expression and tie them into the QueryExpression.
How do each of these relate to a SQL statement? Let’s take our previous SQL query and break it into the related components.
If you were to write this code in C#, it would look something like this:
To run this, you would simply pass the instance of the QueryExpression into the RetrieveMultiple() method and then consume the information from the returned EntityCollection.
There are technically other ways to do this exact same query using LINQ, FilteredViews, or even FetchXML. However, the purpose of this article was to introduce and explain this particular type of querying method. We’ll provide other introductory articles of each these other querying methods later.