Passing multiple GUID to QueryExpression

A few time we need to pass multiple parameters to QueryExpression to fetch required entities. I have seen code with multiple calls instead of passing multiple parameters, and of course avoiding multiple calls is efficient.

In code reviews, I also have seen hard coded Guids or people looping through collections to obtain Guids. In some situations, these can be the “only” or best options but often it can be done in a cleaner way using LINQ.

This code example fetches Guids from an entity collection (which are connections) into Guid[] and then use Guid[] as a parameter in query expression.

EntityCollection result = null;       
//Getting all GUIDs into a Guid array
        Guid[] guids = connections.Entities.Select(con =>

        //Passing guid array in query expression
        QueryExpression query = new QueryExpression("contact");
        query.ColumnSet = new ColumnSet("name");
        query.Criteria.AddCondition(new ConditionExpression("contactid", ConditionOperator.In, guids));
        EntityCollection contacts = organizationService.RetrieveMultiple(query);

I hope it is helpful.

Enjoy your D365 day.

QueryExpression error, “The formatter threw an exception while trying to deserialize the message”

Today I wrote a QueryExpression which was throwing exception “The formatter threw an exception while trying to deserialize the message”.

The complete error message was:

“The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter The InnerException message was ‘Error in line 1 position 2016. Element ‘; contains data from a type that maps to the name ‘;. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name ‘EntityReference’ and namespace ‘;.’. Please see InnerException for more details.”

I was using ‘EntityReference’ in a condition, and error message gives hint that somehow there is an issue with ‘EntityReference’ format, and it is not being deserialized correctly. To use ‘EntityReference’ in condition we need to pass its ‘GUID’, and not complete ‘EntityReference’ object.

In the following QueryExpression, the condition will produce a similar exception which can be avoided by passing GUID instead of passing ‘EntityReference’ object as parameter.

QueryExpression query = new QueryExpression();
query.EntityName = “new_document”;
query.ColumnSet = new ColumnSet(“new_name”);
query.Criteria.AddCondition(“new_authorid”, ConditionOperator.Equal,currentDoc.GetAttributeValue<EntityReference>(“new_authorid”));
EntityCollection results =org.RetrieveMultiple(query);