Forcing recalculation of record counts

Have you ever used the ‘RetrieveTotalRecordCount’ api in Microsoft Dataverse? Using this api, we can retrieve record counts for tables. We can use the OrganizationService or the Web Api to call this message. An example using the Web Api is this:
[DataverseOrgUrl]/api/data/v9.2/RetrieveTotalRecordCount(EntityNames=[‘account’])

This will return the following:

{
    "@odata.context": "https://this-is-an-example-org.crm4.dynamics.com/api/data/v9.2/$metadata#Microsoft.Dynamics.CRM.RetrieveTotalRecordCountResponse",
    "EntityRecordCountCollection": {
        "Count": 1,
        "IsReadOnly": false,
        "Keys": [
            "account"
        ],
        "Values": [
            4
        ]
    }
}

This is very handy for, well, counting rows in a table :). However, this data is not always up to date. It can take anywhere from a few hours to a full day for this data to be updated to the latest state. However, there is a way to force-sync this. By creating a system job of type 46/’Regenerate Entity Row Count Snapshot Data’.

var job = new Entity("asyncoperation");
job["operationtype"] = new OptionSetValue(46);
job["correlationid"] = System.Guid.NewGuid(); // mandatory
job["depth"] = 1; // mandatory
organizationService.Create(job);

Wait for the job to complete. Can take a few minutes. After the job is done, it can take another few minutes to update the snapshot. After that, the RetrieveTotalRecordCount message should show the latest values.

The system job type is (somewhat) documented and can be found here: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/asyncoperation#operationtype-choicesoptions

Related Posts

One thought on “Forcing recalculation of record counts

Leave a Reply

Your email address will not be published. Required fields are marked *