Dynamics CRM 2011

CRM 2011: Get Record Count with FetchXml

On a current project we have to do a full data synchronization between CRM and another data source. CRM has default 5000 maximum record count that can be returned. We can change this value, but a better way is to actually retrieve the records in pages. But to know how many page we need to know how many records. Credits to Fizz for original code.

Using Early Bound code and LINQ, you can call Count(), but that will enumerate the records before giving you the count.

Using FetchXml and aggregate query, we can get the record count.

<fetch mapping='logical' distinct='false' aggregate='true'>
    <entity name='account'>
        <attribute name='accountid' alias='recordcount' aggregate='count'/> 
    </entity>
</fetch>

You can even add filter.

<fetch mapping='logical' distinct='false' aggregate='true'>
    <entity name='account'>
        <attribute name='accountid' alias='recordcount' aggregate='count'/> 
        <filter type="and">
            <condition attribute="statecode" operator="eq" value="0" />
        </filter>
    </entity>
</fetch>

And even link entities.

<fetch mapping='logical' distinct='false' aggregate='true'>
    <entity name='account'>
        <attribute name='accountid' alias='recordcount' aggregate='count'/> 
        <filter type="and">
            <condition attribute="statecode" operator="eq" value="0" />
        </filter>
        <link-entity name="contact" from="contactid" to="primarycontactid">
            <filter type="and">
                <condition attribute="fullname" operator="eq" value="Craig Dunn" />
            </filter>
        </link-entity>
    </entity>
</fetch>

Cheers – Sy

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