public int GetTotalCount(QueryExpression expression, string groupByField = "")
{
var strippedExpression = new QueryExpression(expression.EntityName)
{
ColumnSet = new ColumnSet(false)
{
AttributeExpressions =
{
new XrmAttributeExpression(
attributeName: string.IsNullOrWhiteSpace(groupByField) ? $"{expression.EntityName}id" : groupByField,
alias: $"{expression.EntityName}count",
aggregateType: XrmAggregateType.Count)
}
},
Criteria = expression.Criteria
};
if (expression.LinkEntities.Any())
{
strippedExpression.LinkEntities.AddRange(expression.LinkEntities.Select(l =>
{
l.Columns = new ColumnSet(false);
return l;
}));
}
var response = organizationService.RetrieveMultiple(strippedExpression);
var aliasedValue = response?.Entities?.First().GetAttributeValue<AliasedValue>(($"{expression.EntityName}count"));
return (int) (aliasedValue?.Value ?? 0);
}
Problem
In production environments, the method correctly returns the aggregate count of the QueryExpression. However, in test scenarios, the method retrieves the entities instead of the aggregate count. This behavior is unexpected and leads to incorrect results during testing.
Test method
public void CountLargeList_CountReturnsMoreThan5000()
{
// Arrange
var numberOfTickets = 5050;
var incidents = Enumerable.Range(1, numberOfTickets)
.Select(i => new Incident {
Id = Guid.NewGuid(),
Title = $"Test {i}",
})
.ToList<Incident>();
Context.Initialize(incidents);
// Act
var countResult = _dynamicsService.GetTotalCount(new QueryExpression(Incident.EntityLogicalName));
// Assert
countResult.Should().Be(numberOfTickets);
}
Given this method:
Problem In production environments, the method correctly returns the aggregate count of the QueryExpression. However, in test scenarios, the method retrieves the entities instead of the aggregate count. This behavior is unexpected and leads to incorrect results during testing.
Test method