How to get the option set from a field in an entity in CRM 2011 using crm sdk and C#

Romeo picture Romeo · Apr 27, 2014 · Viewed 10.3k times · Source

How to get the option set from a field in an entity in CRM 2011 using crm sdk and C#? I just want to share with you guys a direct approach on getting the option set of a field in an entity.

Answer

Nicknow picture Nicknow · Apr 29, 2014

The proper way to retrieve metadata information in Dynamics CRM is to retrieve only the information required. We should only retrieve the option set values based on the original question. Retrieving all the metadata for an entity when all the requirement specifies is the values for an Option Set is unnecessary and will create unnecessary overhead.

Here is the correct way to get the list of options for an Option Set.

    public static void GetOptionSet(string entityName, string fieldName, IOrganizationService service)
    {

        var attReq = new RetrieveAttributeRequest();
        attReq.EntityLogicalName = entityName;
        attReq.LogicalName = fieldName;
        attReq.RetrieveAsIfPublished = true;

        var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
        var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;

        var optionList = (from o in attMetadata.OptionSet.Options
            select new {Value = o.Value, Text = o.Label.UserLocalizedLabel.Label}).ToList();


    }