web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

How to get count of records of say contact entity using C#

(0) ShareShare
ReportReport
Posted on by

Hello All,

I was using fetchXML to grab the number of count of Contact entity and I got say 100 records. Now in order to display that in messagebox using C#, can anyone please help me with the code.

I was trying to use - 

string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >

----------

--------

</link-entity>
</entity>
</fetch>";

FetchExpression fetch = new FetchExpression(fetchXml);
EntityCollection results = _service.RetrieveMultiple(fetch);
MessageBox.Show("Count of Records:" + results);

But I know its not correct, please advice me.

*This post is locked for comments

I have the same question (1)
  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Try following:

    MessageBox.Show($"Count of Records: {results.Entities.Count}");

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi Suchi,

    Try with this -

    MessageBox.Show("Count of Records: " + results.Entities.Count);

  • Suggested answer
    Anas Rafik Profile Picture
    365 on at

    Try this

    FetchExpression fetch = new FetchExpression(fetchXml);
    EntityCollection results = _service.RetrieveMultiple(fetch);
    throw new InvalidPluginExecutionException("Count of Records: "+results.Entities.Count);
  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    I have used this in the past for FetchXml Count Aggregate function:

    public static int GetRecordCount(string entityName, string attributeName, ConditionExpression expression)

    {

      int rc = 0;

      StringBuilder sb = new StringBuilder();

      sb.AppendLine("<fetch distinct='false' mapping='logical' aggregate='true'> ");

      sb.AppendLine(" <entity name='" + entityName + "'> ");

      sb.AppendLine("  <attribute name='" + attributeName + "' alias='" + attributeName + "_count' aggregate='count'/> ");

      sb.AppendLine("  <filter type='and'>" );

      if (expression.Values.Count > 1)

      {

        sb.AppendLine("   <condition attribute='" + expression.AttributeName + "' operator='in'>");

        for (int i = 0; i< expression.Values.Count; i++) 

        {

          sb.AppendLine("     <value>" + expression.Values[i].ToString() + "</value>");

        }

        sb.AppendLine("   </condition>");

      }

      else

      {

        sb.AppendLine("   <condition attribute='" + expression.AttributeName + "' operator='eq' value='" + expression.Values[0].ToString() + "' /> ");

      }

      sb.AppendLine("   <condition attribute='statecode' operator='eq' value='0' /> ");

      sb.AppendLine("  </filter> ");

      sb.AppendLine(" </entity> ");

      sb.AppendLine("</fetch>");

      EntityCollection totalCount = OrganizationService.RetrieveMultiple(new FetchExpression(sb.ToString()));

      if (totalCount.Entities.Count > 0)

      {

        foreach (var t in totalCount.Entities)

        {

          rc = (int)((AliasedValue)t[attributeName + "_count"]).Value;

          break;

        }

      }

      return rc;

    }

      

    Hope this helps.

  • Community Member Profile Picture
    on at

    It throws a Nullreferenceexception just at the line :EntityCollection results = _service.RetrieveMultiple(fetch); I am trying to code this inside button event, can that be the cause?

    private void btnUpdate_Click(object sender, EventArgs e)

           {

               string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >

     <entity name='contact'>-------------

    ------------------

    </link-entity>

     </entity>

    </fetch>";

    FetchExpression fetch = new FetchExpression(fetchXml);

    EntityCollection results = _service.RetrieveMultiple(fetch);

    throw new InvalidPluginExecutionException("Count of Records: "+results.Entities.Count);

  • Community Member Profile Picture
    on at

    Thanks for the code, however, I want a messagebox to pop up and show the number of records, and I am unable to place it inside the button event as it wont understand totalcount : - MessageBox.Show($"Count of Records:{totalCount.Entities.Count}"); Can you please be kind enough to advice me...

  • Suggested answer
    Mahendar Pal Profile Picture
    45,095 on at

    Hello,

    Have you created OrganizationService object ?? I think you have created _service object so you need to use that instead (based on your first thread).

    EntityCollection totalCount = _service.RetrieveMultiple(new FetchExpression(sb.ToString()));

  • Community Member Profile Picture
    on at

    Yes Mahen, I figured that out and fixed it and thanlks for your quick reply, but the message box fails to read total count which is stored in public static int GetRecordCount(string entityName, string attributeName, ConditionExpression expression){} and my button_click should pop up the message with the count of record... Can you please help on that !!!

  • Mahendar Pal Profile Picture
    45,095 on at

    Please share your complete code here for checking

  • Community Member Profile Picture
    on at

    Here it is : -

    private void btnUpdate_Click(object sender, EventArgs e)

           {

               string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >

     <entity name='contact'>

       <attribute name='fullname' />

       <attribute name='ownerid' />

       <attribute name='parentcustomerid' />

       <attribute name='aac_palno' />

       <attribute name='mobilephone' />

       <attribute name='jobtitle' />

       <attribute name='telephone1' />

       <attribute name='address1_country' />

       <attribute name='address1_city' />

       <attribute name='emailaddress1' />

       <attribute name='address1_stateorprovince' />

       <attribute name='contactid' />

       <order attribute='parentcustomerid' descending='false' />

       <order attribute='fullname' descending='false' />

       <filter type='and'>

         <condition attribute='statecode' operator='eq' value='0' />

       </filter>

       <link-entity name='account' from='accountid' to='parentcustomerid' visible='false' link-

    type='outer' alias='a_******************5'>

         <attribute name='accountnumber' />

         <attribute name='aac_nearestairportid' />

       </link-entity>

     </entity>

    </fetch>";

              MessageBox.Show($"Count of Records:{totalCount.Entities.Count}");

           }

           public static int GetRecordCount(string fetchXml, string attributeName, ConditionExpression expression)

           {

               int rc = 0;

               StringBuilder sb = new StringBuilder();

               sb.AppendLine("<fetch distinct='false' mapping='logical' aggregate='true'> ");

               sb.AppendLine(" <contact='" + fetchXml + "'> ");

               sb.AppendLine("  <attribute name='" + attributeName + "' alias='" + attributeName + "_count' aggregate='count'/> ");

               sb.AppendLine("  <filter type='and'>");

               if (expression.Values.Count > 1)

               {

                   sb.AppendLine("   <condition attribute='" + expression.AttributeName + "' operator='in'>");

                   for (int i = 0; i < expression.Values.Count; i++)

                   {

                       sb.AppendLine("     <value>" + expression.Values[i].ToString() + "</value>");

                   }

                   sb.AppendLine("   </condition>");

               }

               else

               {

                   sb.AppendLine("   <condition attribute='" + expression.AttributeName + "' operator='eq' value='" + expression.Values[0].ToString() + "' /> ");

               }

               sb.AppendLine("   <condition attribute='statecode' operator='eq' value='0' /> ");

               sb.AppendLine("  </filter> ");

               sb.AppendLine(" </entity> ");

               sb.AppendLine("</fetch>");

               EntityCollection totalCount = _service.RetrieveMultiple(new FetchExpression(sb.ToString()));

               if (totalCount.Entities.Count > 0)

               {

                   foreach (var t in totalCount.Entities)

                   {

                       rc = (int)((AliasedValue)t[attributeName + "_count"]).Value;

                       break;

                   }

               }

               return rc;

           }

           }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans