Search This Blog

Tuesday, May 21, 2019

Get Sum/Aggregate from Related entity using c# in Dynamics CRM

public int GetTotal()
{
FetchExpression f1 = new FetchExpression("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' aggregate='true' >" +
                    "    <entity name='account' >" +
                    "        <filter type='and' >" +
                    "            <condition attribute='statuscode' operator='in' >" +
                    "                <value>" +
                    "                    1" +
                    "                </value>" +
                    "                <value>" +
                    "                    175650000" +
                    "                </value>" +
                    "            </condition>" +
                    "        </filter>" +
                    "        <link-entity name='batch' from='batchid' to='batchid' visible='false' link-type='outer' alias='bc' >" +
                    "            <attribute name='credithour' aggregate='sum' alias='totalcredithours' />" +
                    "        </link-entity>" +
                    "    </entity>" +
                    "</fetch>");

EntityCollection AccountCollection = service.RetrieveMultiple(f1);
                int total = 0;
                if (AccountCollection != null)
                {
                    AccountCount = AccountCollection.Entities.Count;
                    if (AccountCount > 0)
                    {
                        foreach (var entity in AccountCollection.Entities)
                        {
                            if (entity.Attributes.Contains("totalcredithours"))
                            {
                                total = Convert.ToInt16(((AliasedValue)entity.Attributes["totalcredithours"]).Value);
                            }
                            return total;
                        }
                    }
                }
}


No comments:

Post a Comment