Retrieve Option Set Metadata in C#

Given the name of an entity and the name of an option set field, Microsoft.Xrm.Sdk.Messages can retrieve all the labels and corresponding integer values for an option set.

Simply build a new RetrieveAttributeRequest and iterate over the response like so:

var attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "entityName",
LogicalName = "attributeName",
RetrieveAsIfPublished = true
};
var attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
var attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;
var optionList = (from o in attributeMetadata.OptionSet.Options
select new { Value = o.Value, Text = o.Label.UserLocalizedLabel.Label }).ToList();

optionList now contains a list of all option set options where each object in the list has a Value property and a Text property.

To retrieve a given option set value for a label, use a Linq query:

var activeValue = optionList.Where(o => o.Text == "Active")
.Select(o => o.Value)
.FirstOrDefault();

2 comments:

  1. What is Active here It is giving me null value?

    ReplyDelete
  2. Great content. To the point and addressing an issue that few others have shared a solution for.

    ReplyDelete