private OptionsModel GetRecordsManyToManyGroupBy(string entityLogicalName, string attributeLogicalName, string groupByAttributeLogicalName, string intersectEntityName, OptionsModel optionsModel) { var query = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' aggregate='true'> <entity name='{entityLogicalName}'> <attribute name='{groupByAttributeLogicalName}' groupby='true' alias='group'/> <attribute name='{groupByAttributeLogicalName}' aggregate='count' alias='count'/> <link-entity name='{intersectEntityName}' from='{entityLogicalName}id' to='{entityLogicalName}id' visible='false' intersect='true'> <link-entity name='{Record.LogicalName}' from='{Record.LogicalName}id' to='{attributeLogicalName}' alias='aa'> <filter type='and'> <condition attribute='{Record.LogicalName}id' operator='eq' value='{Record.Id}'/> </filter> </link-entity> </link-entity> </entity> </fetch>"; EntityCollection result = Service.RetrieveMultiple(new FetchExpression(query)); foreach (var item in result.Entities) { int?value = null; if (item.Contains("group")) { var groupby = ((AliasedValue)item["group"]).Value; // Define the type if (groupby.GetType() == typeof(OptionSetValue)) { value = ((OptionSetValue)groupby).Value; } else if (groupby.GetType() == typeof(Boolean)) { value = Convert.ToInt32((Boolean)groupby); } } else { value = null; } // Get the right option var option = optionsModel.GetOption(value); if (option != null) { option.Count = (Int32)((AliasedValue)item["count"]).Value; } } return(optionsModel); }