If you’ve ever written more complex plugins that retrieve data of linked entities, chances are you’ve come across the AliasedValue object… and had a hard time with it. We’re here to help you with that!

What is AliasedValue?

Simply put, these AliasedValues are wrappers which wrap the actual entity attribute of a LinkedEntity. Furthermore, they are also used as a wrapper when using Aggregate FetchXml’s. Full specifications for the AliasedValue can be found on MSDN.

While these AliasedValues are great, it does require you to code a few extra lines when using these AliasedValues. I’m sure you’ve already encountered stuff like this – this is the code example of the MSDN page mentioned above:

// Fetch the average of estimatedvalue for all opportunities.  This is the equivalent of 
// SELECT AVG(estimatedvalue) AS estimatedvalue_avg ... in SQL.
string estimatedvalue_avg = @" 
<fetch distinct='false' mapping='logical' aggregate='true'> 
	<entity name='opportunity'> 
	   <attribute name='estimatedvalue' alias='estimatedvalue_avg' aggregate='avg' /> 

EntityCollection estimatedvalue_avg_result = _serviceProxy.RetrieveMultiple(new FetchExpression(estimatedvalue_avg));

foreach (var c in estimatedvalue_avg_result.Entities)
	decimal aggregate1 = ((Money)((AliasedValue)c["estimatedvalue_avg"]).Value).Value;
	System.Console.WriteLine("Average estimated value: " + aggregate1);


Pay attention to the highlighted line:


That’s not very easing on the eye, is it? When adding the required Null-checks in there you soon end up with 4 lines of code for each AliasedValue you want to use.

Extension Method GetAttributeAliasedValue

The snippet below is an Extension Method (MSDN link here) that allows us to add another method to the Entity object, resulting in us being able to use the AliasedValue’s much in the same way we access other attributes:

decimal aggregate1 = c.GetAliasedAttributeValue<Money>("estimatedvalue_avg").Value;

Simply add the code below as a new class, and reference the Thrives.ExtensionMethods namespace to be able to use the GetAliasedAttributeValue as shown above.

using Microsoft.Xrm.Sdk;

namespace Thrives.ExtensionMethods
    public static class ExtensionMethods
        public static T GetAliasedAttributeValue<T>(this Entity entity, string attributeName)
            if (entity == null)
                return default(T);

            AliasedValue fieldAliasValue = entity.GetAttributeValue<AliasedValue>(attributeName);

            if (fieldAliasValue == null)
                return default(T);

            if (fieldAliasValue.Value != null && fieldAliasValue.Value.GetType() == typeof(T))
                return (T)fieldAliasValue.Value;

            return default(T);

Happy coding!