CRM 2011 – odd error with Query Expression and ConditionOperator.In

I found an odd error with OptionSetValues and ConditionOperator in when doing a query expression.

I was doing a query expression which retrieved some account records where an optionSet was either Bill to or Ship to.  So using a query expression I used the ConditionOperator.In and selected the two values.

Now the wierd this is the below examples works

ConditionExpression condition3 = new ConditionExpression();
condition3.AttributeName = “chw_appointmenttype”;
condition3.Operator = ConditionOperator.In;
condition3.Values.Add(new object[] { new OptionSetValue(126740001).Value, new OptionSetValue(126740000).Value });

This one doesn’t work

OptionSetValue op3 = new OptionSetValue(1);
OptionSetValue op4 = new OptionSetValue(3);
QueryExpression newquery1 = new QueryExpression(“contact”);
newquery1.ColumnSet = new ColumnSet(“fullname”);
newquery1.Criteria.AddCondition(new ConditionExpression(“address1_addresstypecode”, ConditionOperator.In, new int[] { op3.Value, op4.Value }));

Now unfortunatly for me I was using the second example and couldn’t understand why the query was erroring because it all looked ok.

Finally I had to search the internet and found this blog

below is his explanation

QueryExpression q = new QueryExpression(“annotation”);
Guid g1 = Guid.NewGuid();
Guid g2 = Guid.NewGuid();
q.Criteria.AddCondition(new ConditionExpression(“objectid”, ConditionOperator.In, new Guid[] { g1, g2 }));

However, change the last line to the following, and it fails with the error above:

q.Criteria.AddCondition(“objectid”, ConditionOperator.In, new Guid[] { g1, g2 });

On the face of it, you’d expect identical behaviour, but it looks like the problem is due to the parameter overloads on the different methods. The constructor for ConditionExpression takes 5 overloads, and the compiler will use System.Collections.ICollection for the array of Guids. However, the AddCondition method only offers one type for the third parameter (params object[]). The result of this is that the code fails because the parameter is interpreted as object[] {new Guid[] { g1, g2 }}.

Interestingly, other code can also work, e.g.

q.Criteria.AddCondition(“objectid”, ConditionOperator.In, new object[] { g1, g2 });
q.Criteria.AddCondition(“objectid”, ConditionOperator.In, g1, g2);

Leave a Reply

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

You are commenting using your 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