Search code examples
pluginsdynamics-crmmicrosoft-dynamicsdynamics-crm-2016fetchxml

System.InvalidCastException ("Specified cast is not valid.") in a FetchXML query for an OptionSet Attribute


I am trying to retrieve the numeric value of each OptionSet returned by a FetchXML Query. The value retrieved is aliased and I want to cast the aliased value into an integer and store each value into a list. The system gives me an InvalidCastException each time, what should I do to fix this ???

Invalid Cast Exception

Here is the code being used...

//Initialize serving Group list
                    var servingGroup = new List<int>();

                    string servingGroups = @"   <fetch distinct='true' >
                        <entity name='contract' >
                            <link-entity name='contractdetail' from = 'contractid' to = 'contractid' >
                                <attribute name='new_servinggroup' alias='new_servinggroup_av' />
                                <filter type='and' >
                                    <condition value='0' attribute='statecode' operator= 'eq' />
                                    <condition value='" + targetId + @"' attribute='contractid' operator= 'eq' />
                                </filter >                                          
                            </link-entity> 
                         </entity >
                     </fetch>";

                    EntityCollection servingGroups_result =
                        service.RetrieveMultiple(new FetchExpression(servingGroups));

                    foreach (var serving in servingGroups_result.Entities)
                    {
                        var value = (int)(serving.GetAttributeValue<AliasedValue>("new_servinggroup_av").Value);
                        servingGroup.Add(value);

                    }

Solution

  • Please see the below self-explained data conversion or valid casting. You can do this in Immediate window or see this in Quick watch when debugging in Visual studio. Or simply mouse-hover each variable to learn more from VS tips and intellisense.

    AliasedValue aliasedValue = serving.GetAttributeValue<AliasedValue>("new_servinggroup_av");
    object aliasValue = aliasedValue.Value;
    OptionSetValue optionSet = (OptionSetValue)aliasValue;
    int optionSetValue = optionSet.Value;
    
    var value = (int)optionSetValue;
    

    Alternate:

    var value = (int)((OptionSetValue)(serving.GetAttributeValue<AliasedValue>("new_servinggroup_av").Value).Value);