CRM 2011 – How to do Like statement in QueryExpression

I was trying to do a like statement in a query expression and it took me a while to work out how to do it.
the first thing you do is use the Like condidationOperator and then you add the value.  Like an SQL query you need to use
the % wildcard and add this to the text string
            condition1.Operator = ConditionOperator.Like;
            //ConditionOperator.Like
            condition1.Values.Add(id.ToLower() + "%");

the other interesting aspect of the sample code below is I cast the results

 IEnumerable<hosk_candidate> newCandidates = result1.Entities.Cast<hosk_candidate>();

The reason I had to do this was because I was changing how I selected the data from CRM from LINQ queries to
QueryExpressions because LINQ statements cannot be used in CRM Online.

 private IEnumerable<hosk_candidate> selectCandidates(hosk_candidate candidate, string id)
        {

            ConditionExpression condition1 = new ConditionExpression();
            condition1.AttributeName = "hosk_candidatehoskid";
            condition1.Operator = ConditionOperator.Like;
            //ConditionOperator.Like
            condition1.Values.Add(id.ToLower() + "%");

            FilterExpression filter1 = new FilterExpression();
            filter1.Conditions.Add(condition1);

            QueryExpression query = new QueryExpression("hosk_candidate");
            query.ColumnSet.AddColumns("hosk_candidatehoskid");
            query.Criteria.AddFilter(filter1);

            EntityCollection result1 = service.RetrieveMultiple(query);
            IEnumerable<hosk_candidate> newCandidates = result1.Entities.Cast<hosk_candidate>();

            return newCandidates;
        }
Advertisements

2 thoughts on “CRM 2011 – How to do Like statement in QueryExpression

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s