FetchXml from ToString()

Jun 9, 2010 at 4:32 PM

I read through the documentation on the Adxstudio Developer Community site and was excited to find out that calling ToString() on an XRM LINQ expression should return the underlying FetchXML. When I tried this, however, I couldn't get it to work. I experimented with the example in the documentation as well as a few other simple LINQ statements to no avail. It seems that I can manually perform the the conversion by extracting the Expression and making the QueryExpressionToFetchXmlRequest but for some reason the ToString() method simply returns the type as it would with the default implementation. Is there something I should be doing differently to get the ToString() method to return the query FetchXML?

static void Main(string[] args)
    XrmDataContext context = new XrmDataContext();

    string fetchXml = string.Empty;
    var xrmQuery = context.phonecalls.Where(p => p.subject.Contains("Test")).Select(p => p);
    // Doesn't work - returns 'Microsoft.Xrm.Client.Linq.Query`1[Xrm.phonecall]'
    fetchXml = xrmQuery.ToString();

    // Works
    Expression exp = xrmQuery.Expression;
    QueryExpression queryExp = context.Translate(exp);
    IOrganizationService service = context.CreateService();
    QueryExpressionToFetchXmlResponse fetchXmlResponse = 
        (QueryExpressionToFetchXmlResponse)service.Execute(new QueryExpressionToFetchXmlRequest() { Query = queryExp });
    fetchXml = fetchXmlResponse.FetchXml;




Jun 9, 2010 at 6:14 PM

The .ToString() mechanism got changed when we refactored the SDK to deliver to Microsoft.  Here is a code snippet on how to use it with the new SDK:

var crm = new XrmDataContext(CrmConnection.Parse("Authentication Type=Integrated; Server=http://CRM/Adxstudio"));
var contacts = from c in crm.contacts
        where c.emailaddress1.EndsWith("@adxstudio.com")
        select c;
var QE = crm.Translate(contacts.Expression);
var Fetch = crm.UsingService(service =>
    return service.QueryExpressionToFetchXml(QE);

Jun 15, 2010 at 5:32 PM

It looks like Microsoft's documentation in the CRM SDK (4.0.12) incorrectly states that the ToString() method translates the current LINQ expression to FetchXML. This incorrect entry is in both the .chm and on MSDN


Jun 15, 2010 at 5:59 PM

We are aware of the inconsistency in the documentation and will be resolving that in the next release of the SDK.  The example that I gave is the official way to do this.


Jun 15, 2010 at 6:00 PM

Thanks Shan

Sep 16, 2010 at 2:12 PM
Edited Sep 17, 2010 at 7:31 AM


Is it possible to do the reverse process ? I have a QueryExpression and i want to convert it in a Linq Expression ?