FetchXML查询中对OptionSet属性

时间:2018-07-25 18:05:32

标签: plugins dynamics-crm microsoft-dynamics dynamics-crm-2016 fetchxml

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

Invalid Cast Exception

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

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

                    }

1 个答案:

答案 0 :(得分:3)

请参见下面的自解释数据转换或有效转换。您可以在“即时”窗口中执行此操作,也可以在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);