CRM 2015 FetchXML Aggregates not working in Plugins Anymore

Paul Nieuwelaar, 28 May 2015

If you've started receiving random NullReferenceException errors when executing your plugins after upgrading to CRM 2015, this might be why. When performing SUM aggregates in plugins, for some reason now, if there are no records for that entity, instead of giving you no results like it used to, you now get a result, however the 'Value' of the AliasedValue that gets returned from the aggregate is null, which causes casting errors.

This is a code snippet from the SDK, which you can see is crashing when it tries to get the value of the aggregate. This is because we have no opportunities in our system. If there were 1 or more opportunities we would not get the error. In previous versions of CRM, the code would have skipped over the foreach loop as there'd be no results returned by the aggregate.

The short answer is to check for null on the AliasedValue.Value before trying to cast it. This means if you have one-liners like the SDK does, you'll have to break these down.

AliasedValue a = (AliasedValue)c["estimatedvalue_sum"];
if (a.Value != null)
{
decimal aggregate7 = ((Money)a.Value).Value;
System.Console.WriteLine("Sum of estimated value of all opportunities: " + aggregate7);
}

Because a.Value will be null when there are no results, the code will now skip over casting it to Money, and it will prevent it from crashing.

This issue only appears to happen with SUM aggregates, and works fine with COUNT (Value will be 0 if no results).