Thursday, October 13, 2011

Convert QueryExpression To FetchXml

Converting fetch xml to query expression and vice-verse was not an easy job for the developers and was very much complicated if you have a complex query with multiple link entities and criteria. Currently CRM 2011 provides the functionality to generate fetch xml using advanced find which could be used within the code with necessary changes. But if we have a query expression which need to be implemented within javascript for client side implementations, then QueryExpressionToFetchXmlRequest will be very useful.

The following example explains a simple conversion of query expression request to fetch xml.

QueryExpression query = new QueryExpression()
EntityName = "product",
ColumnSet = new ColumnSet(false),
Distinct = true,
Criteria = new FilterExpression()
FilterOperator = LogicalOperator.And,
Conditions =
new ConditionExpression("statecode",ConditionOperator.Equal, "0" )

QueryExpressionToFetchXmlRequest fetchxmlrequest = new QueryExpressionToFetchXmlRequest();
fetchxmlrequest.Query = query;

QueryExpressionToFetchXmlResponse queried = (QueryExpressionToFetchXmlResponse)crmservice.Execute(fetchxmlrequest);
string fetchXml = queried.FetchXml;

The below example explains the conversion of generated fetch xml request string to query expression.

FetchXmlToQueryExpressionRequest queryrequest = new FetchXmlToQueryExpressionRequest();
queryrequest.FetchXml = fetchXml;

FetchXmlToQueryExpressionResponse response = (FetchXmlToQueryExpressionResponse)crmservice.Execute(queryrequest);

QueryExpression query = response.Query;

Good Luck!


Gogy said...
This comment has been removed by the author.
Gogy said...

Is it possible make convertation without OrganizationService.Execute?