Retrieve Data using FetchXML to Construct a Query

Retrieve Data using FetchXML to Construct a Query

To execute a FetchXML query in Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online, you must first build the XML query string. After you create the query string, use the IOrganizationService.RetrieveMultiple method to execute the query string. The privileges of the logged on user affects the set of records returned. Only records for which the logged on user has read access will be returned.

he FetchXML query string must conform to the schema definition for the FetchXML language. For more information, see FetchXML Schema.

Set visible on the link-entity node to false to hide the linked entity in the Advanced Find user interface. It will still participate in the execution of the query and will return the appropriate results.

Create the Query String

In the following example, the FetchXML statement retrieves all accounts:

<fetch mapping='logical'> 
   <entity name='account'><all-attributes/></entity>
</fetch>

In the following example, the FetchXML statement retrieves all accounts where the last name is not equal to Cannon:

<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='Cannon' /> 
          </filter> 
      </link-entity> 
   </entity> 
</fetch>

Execute the Query

The following code shows how to execute a FetchXML query:

// Retrieve all accounts owned by the user with read access rights to the accounts and 
// where the last name of the user is not Cannon. 
string fetch2 = @"
   <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='Cannon' /> 
           </filter> 
        </link-entity> 
     </entity> 
   </fetch> "; 
EntityCollection result =_serviceProxy.RetrieveMultiple(new FetchExpression(fetch2));

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

Cheers,
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s