Hi,
There are other options problably to do what you are looking for, but you can use the following function to calculate an Aggregate values:
private int GetAggregateValue(string entityName, string attributeName, ConditionExpression expression)
{
decimal 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 + "_sum' aggregate='sum'/> ");
sb.AppendLine(" <filter type='and'>");
sb.AppendLine(" <condition attribute='" + expression.AttributeName + "' operator='eq' value='" + expression.Values[0].ToString() + "' /> ");
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 = (decimal)((AliasedValue)t[attributeName + "_sum"]).Value;
break;
}
}
return rc;
}
You can call it the following way:
ConditionExpression exp = new ConditionExpression("new_parentid", ConditionOperator.Equal, parentId);
decimal totalAmount = GetAggregateValue("new_child", "new_amount", exp);
Entity parent = new Entity("new_parent");
parent.Id = parentId;
parent["new_total_amount"] = new Money(totalAmount);
service.Update(parent);
Hope this helps.