System.InvalidCastException ("Specified cast is not valid.") 在 OptionSet 属性的 FetchXML 查询中

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

我正在尝试检索 FetchXML 查询返回的每个 OptionSet 的数值。检索到的值是别名的,我想将别名值转换为整数并将每个值存储到列表中。系统每次都给我一个InvalidCastException,我应该怎么做才能解决这个问题???

这是正在使用的代码...

//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);

                    }

请参阅下面的自我解释数据转换或有效转换。您可以在立即 window 中执行此操作,或者在 Visual studio 中调试时在快速观察中查看此操作。或者只需将鼠标悬停在每个变量上,即可从 VS 提示和智能感知中了解更多信息。

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

var value = (int)optionSetValue;

备用:

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