Search code examples
c#dynamics-crmcrm

Converting object type to Microsoft.Xrm.Sdk.OptionSetValue type


I am writing a program that uses the Microsoft Dynamics CRM API to populate a form with information gained from an EntityCollection given by the CRM. My issue is that the Entity is comprised of KeyValuePair<string, object> and this is causing a headache. some of the objects in the kvps are of type OptionSetValue during runtime and I need a way actually access the value because OptionSetValue require an additional accessor.

Here's some example code to demonstrate my problem ('e' is the Entity):

foreach (KeyValuePair<string, object> thePair in e.Attributes.ToList())
{
    int theResult = thePair.Value;
}

In the above example the program will compile but will throw an expection during runtime because it will try to convert from OptionSetValue to int32.

Here's what I would like to accomplish somehow:

foreach (KeyValuePair<string, object> thePair in e.Attributes.ToList())
{
    int theResult = thePair.Value.Value;
}

In this scenario the .Value accessor would return the value I need, but since the C# compiler does not know that thePair is of type OptionSetValue until runtime, it will not compile because the object type does not have a .Value member.

Any thoughts or need for clarification on my issue?


Solution

  • It seems typing this all out have given me some clarity as I fixed this issue less than 5 minutes after this post. You can simply typecast use (OptionSetValue)

    foreach (KeyValuePair<string, object> thePair in e.Attributes.ToList())
    {
        int theResult = (OptionSetValue)thePair.Value.Value;
    }