Convert CRM2011 LINQ Query into QueryExpression / FetchXml

With the introduction of Linq within the Dynamics CRM 2011 sdk, I've more or less stopped using QueryExpressions and FetchXml in server side code. This makes it increasingly painful when I've got to convert my queries to fetchXml or QueryExpressions for use in Javascript or Silverlight code. This sample shows how you can convert those linq queries into a QueryExpression or FetchXml by way of a command line utility.

This is a useful tool for debugging your linq queries as well to check that they are going to execute as you expect - however I would highly recommend LinqPad for a more indepth debuger/learning tool (

This sample also demonstrates how to compile a Linq query from a text string - although this is something that shouldn't be done to get round the lack of dynamic query support in Linq - please see :  for an example of how to do this.

The main challenge was how to find the Query Expression from a linq query. This is solved by accessing a private method named 'GetQueryExpression'. 

QueryExpression query = (QueryExpression)linq.Provider.GetType().InvokeMember("GetQueryExpression", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, linq.Provider, arguments);

When you run the sample, you are prompted first to enter the details of your CRM server, and then you can enter a linq query. The Context must be named ctx - so a query would look like:

>from c in ctx.CreateQuery<Contact>()
>select c

To convert your query, simply press enter with a blank line.

The query is output to the console as well as saved as a text file for future reference.

Download Sample

Comments are closed