Tuesday, March 16, 2021

Dynamics 365 Use FetchXML to query data

 Use FetchXML to construct a query in Plugin, Console App, C#, and Workflow

1. FetchXML is a proprietary query language that is used in Microsoft Dataverse.
2. A FetchXML query can be executed by using either the Web API or the Organization service.
3. To execute a FetchXML query, you must first build the XML query string. After you create the query string, use the IOrganizationService.RetrieveMultiple method to execute the query string.
4. This FetchXML query can be used in C# codePlugin, Custom Workflow, and Console App.
5. For this to work correctly, you must be connected to the server to get an IOrganizationService interface.

Here in this blog, I'm going to show using organization service 

Click here to convert fetchxml query to the query expression

Use the IOrganizationService.RetrieveMultiple method passing a FetchExpression where the Query property contains the FetchXml query.

The below code shows how to execute a FetchXML query using the Organizations Service:

// Retrieve all accounts owned by the user with read access rights to the accounts and // where the last name of the user is not Kumar.

string fetchxml = @"<fetch mapping='logical'> 
                      <entity name='account'>  
                        <attribute name='accountid'/>  
                        <attribute name='name'/>  
                          <link-entity name='systemuser' to='owninguser'>  
                            <filter type='and'>  
                            <condition attribute='lastname' operator='ne' value='Kumar' />  
                            </filter>  
                          </link-entity>  
                       </entity>  
                     </fetch> ";

EntityCollection result = _service.RetrieveMultiple(new FetchExpression(fetchxml));

foreach (var c in result.Entities) { System.Console.WriteLine(c.Attributes["name"]); }


Refer to MS Docs for more details.


Thank you ...
Happy CRMing...

Keep Learning!!!