Friday, July 27, 2012

Getting the Text Value of an OptionSetValue Using LINQ in Microsoft Dynamics CRM 2011

I have seen some interesting things historically when trying to get at the text value of an OptionSetValue in code.  Many times this means making a metadata RetrieveAttributeRequest or something of that nature to get the metadata for the OptionSet.  This is pretty cumbersome in many instances, but the other day I saw an interesting way of doing this put out in a forum question here.

The basics are as follows.

1. Use CrmSvcUtil.exe (comes with the SDK) to get a context that you can use with the CRM LINQ provider.

2. Use LINQ to pull the entity attribute FormattedValues for a specific attribute of type OptionSetValue.  The example below is pulling based on a specific entity ID so it pulls the specific text value of the optionset in this instance.


var strstringvalue = (from ca in context.CreateQuery<CampaignActivity>()
        where ca.ActivityId == campaignResponse.new_CampaignActivityId.Id
        select ca.FormattedValues["new_campaignactivitytype"]);



This should help somebody out. :) - Happy Friday!

1 comment:

  1. what if we need to compare the optionset labels with a parameter? can we do it in where clause?

    ReplyDelete