For version 9.0 please check the below post
RetrieveTotalRecordCountRequest
https://dreamingincrm.com/2019/07/22/getting-entity-record-counts/
Just sharing a sample code to get the total number of records (e.g. account here)
<br />
IOrganizationService orgService = GetOrganizationService();</p>
<p> int totalCount = 0;</p>
<p> QueryExpression query = new QueryExpression("account");<br />
query.ColumnSet = new ColumnSet();<br />
query.Distinct = true;<br />
query.ColumnSet.AddColumn("accountid");<br />
query.PageInfo = new PagingInfo();<br />
query.PageInfo.Count = 5000;<br />
query.PageInfo.PageNumber = 1;<br />
query.PageInfo.ReturnTotalRecordCount = true;</p>
<p> EntityCollection entityCollection = orgService.RetrieveMultiple(query);<br />
totalCount = entityCollection.Entities.Count;</p>
<p> while (entityCollection.MoreRecords)<br />
{<br />
query.PageInfo.PageNumber += 1;<br />
query.PageInfo.PagingCookie = entityCollection.PagingCookie;<br />
entityCollection = orgService.RetrieveMultiple(query);<br />
totalCount = totalCount + entityCollection.Entities.Count;<br />
} </p>
<p> MessageBox.Show(totalCount.ToString());<br />
Hope it helps
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.

While this certainly works, it is not a very efficient solution. You are downloading and enumerating all accounts in the system when all you really want is the total count. Instead I would suggest you take a look at FetchXML aggregation: https://msdn.microsoft.com/en-us/library/gg309565.aspx#count
LikeLike
Thanks ! It would fail in case of more that 50000 records
System.ServiceModel.FaultException`1: ‘AggregateQueryRecordLimit exceeded. Cannot perform this operation.’
LikeLike
it’s work on account Entity
i change the QueryExpression to other Entity,
when i got the error “Paging cookie is required when trying to retrieve a set of records on any high pages”
LikeLike
i found the problem,the target field must include the primary key
LikeLike