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 http://schemas.microsoft.com/xrm/2011/Contracts/Services:query. The InnerException message was ‘Error in line 1 position 2016. Element ‘http://schemas.microsoft.com/2003/10/Serialization/Arrays:anyType’ contains data from a type that maps to the name ‘http://schemas.microsoft.com/xrm/2011/Contracts:EntityReference’. 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 ‘http://schemas.microsoft.com/xrm/2011/Contracts’.’. 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);