"Unable to cast object of type 'Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata' to type 'Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata' " RRS feed

  • Question

  • I have a method to retrieve an Option Set's value given the text:

    public static int GetOptionSetValueGivenText(IOrganizationService service, string entityName, string attributeName, string selectedValue, string FieldInQuestion)
                        RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true };
                        RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                        PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                        OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                        int selectedOptionValue = -1;
                        foreach (OptionMetadata oMD in optionList)
                            if (oMD.Label.UserLocalizedLabel.Label == selectedValue)
                                selectedOptionValue = oMD.Value.Value;
                        return selectedOptionValue;
                    catch (System.ServiceModel.FaultException ex1)
                        WriteToEventLog(0, ex1.Message + " " + ex1.InnerException, FieldInQuestion);
                        return -1;
                    catch (Exception ex)
                        WriteToEventLog(0, ex.Message + " " + ex.InnerException, FieldInQuestion);
                        return -1;

    This works well for a half-dozen custom option sets in my Contact records.

    I just added a new call to this method and I am getting the error in the Subject line of the post on the line that is bolded above:
    "Unable to cast object of type 'Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata' to type 'Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata' "

    The call looks like:

    fieldValue = GetOptionSetValueGivenText(service, Xrm.

    ce_zipxref.EntityLogicalName, "ce_timezone", fieldText, "Time Zone");

    Can someone explain why I am getting this error now?

    Thursday, June 21, 2012 9:31 PM


All replies

  • what type of attribute is "ce_timezone"?

    Thursday, June 21, 2012 9:52 PM
  • Thanks for the hint, Mesganaw. That and a good night's sleep led me to the answer.name of the option set itself instead of the attribute name of that option set on the Contact record.  Works now!

    Friday, June 22, 2012 12:16 PM