Search code examples
c#asp.net-coredynamics-crmdynamics-365

How do I set the value of an OptionSet in Dynamics 365 CRM API in ASP.NET Core?


I'm trying to update an existing Dynamics 365 account attribute that is an optionset. I've created a dictionary with the value: intId where the intId is the Dynamics 365's ID for that particular attribute value.

The code below has worked for multiselect options where you concatenate all the numeric ids, separated by a comma, but when I try with an optionset, it says

The property provided was of type System.String, when the expected was of type System.Int32

var config = new ServiceConfig(ConnectionString);

using (var service = new CDSWebApiService(config))
{
    string url = $"{BaseUrl}accounts({dynGuid})";
    //var jContent = (JObject)JToken.FromObject(accountType);
    //.put accepts the url, attribute to change, and the value to apply
    service.Put(url, "customertypecode", customerTypeCode);
}

The customerTypeCode being sent is "#########" where it's the appropriate 9 digit Id in D365. Do I need to overload the put method for attributes expecting integer values like customertypecode?

The method above is nearly identical to the one used to set a multiselect attribute, where the value passed for the third parameter was the concatenated string of int Ids for the attribute value in D365. I'm not sure why it's now throwing that error other than optionset must behave differently than multiselect attributes.

I can't seem to find documentation on optionsets other than how to insert more values into them in D365, but I know I'm missing something obvious.


Solution

  • It looks like creating the body as an object and sending the request using Patch instead of Put did the trick. It just takes the Uri and JObject representing the body and updated the record accordingly.

    var accountType = new
                      {
                         customertypecode = customerTypeString
                      };
    
    string url = $"{BaseUrl}accounts({dynGuid})";
    Uri updateUrl = new Uri(url);
    
    var jContent = (JObject)JToken.FromObject(accountType);
    
    service.Patch(updateUrl, jContent);