Retrieve Optionsets in Dynamics 2011

2019-07-02 11:30发布

问题:

I am using this code to retrieve global optionsets

var request = new RetrieveOptionSetRequest {Name = "OptionsetNameGoesHere"};
var retrieveOptionSetResponse =(RetrieveOptionSetResponse) DynamicsHandler._serviceProxy.Execute(request);
var retrievedOptionSetMetadata =(OptionSetMetadata) retrieveOptionSetResponse.OptionSetMetadata;
var optionList = retrievedOptionSetMetadata.Options.ToArray();

foreach (var optionMetadata in optionList)
{
   Printout(optionMetadata.Label.LocalizedLabels[0].Label + "\n");
}

But how do I retrieve optionsets like AccountCategory (AccountCategoryCode) so that I can bind them to a Combobox?

回答1:

You should get it with a RetrieveAttributeRequest. It will return an RetrieveAttributeResponse which contains the Property AttributeMetadata.

In your case it should be of type OptionSetMetadata, which is what you are looking for.



回答2:

This is how I have solved this problem. CRMBase is my base class with connection to the CRM instance. Codelanguage: C#

public static Dictionary<int, string> GetAll(CRMBase conn, string entityName, string attributeName)
{
     OptionMetadataCollection result = RetrieveOptionSetMetaDataCollection(conn, entityName,           attributeName);
     return result.Where(r => r.Value.HasValue).ToDictionary(r => r.Value.Value, r => r.Label.UserLocalizedLabel.Label);
}

// Method to retrieve OptionSet Options Metadadata collection.
private static OptionMetadataCollection RetrieveOptionSetMetaDataCollection(CRMBase conn, string prmEntityName, string prmAttributeName)
{
     RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest();

     retrieveEntityRequest.LogicalName = prmEntityName;

     retrieveEntityRequest.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes;

     RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)conn._orgContext.Execute(retrieveEntityRequest);

     return (from AttributeMetadata in retrieveEntityResponse.EntityMetadata.Attributes where 
     (AttributeMetadata.AttributeType == AttributeTypeCode.Picklist & AttributeMetadata.LogicalName == prmAttributeName) 
     select ((PicklistAttributeMetadata)AttributeMetadata).OptionSet.Options).FirstOrDefault();
}