I'm not sure why my code is being formatted like that, so here it is posted directly into the box.
//entity is of type Microsoft.Xrm.sdk.Entity
//CrmFieldName is of type String
// This function queries the dataverse table to determine if the CrmFieldName we are testing is a picklist
// Is there a better way to do this? I'd rather not query for each and every field if possible
// OR is it possible that Dynamics is optimized so that this is not a performance concern?
PicklistAttributeMetadata picklist = queryForPicklistMetadata(entity, CrmFieldName);
if (picklist != null)
{
tracingService?.Trace("Picklist detected");
bool matchFound = false;
foreach (OptionMetadata option in picklist.OptionSet.Options)
{
// If the label of the integer representation of the value matches what we think the value should be
if (option.Label.UserLocalizedLabel.Label == sFieldValue)
{
tracingService?.Trace("Matching Picklist Option found : "+ option.Value.ToString());
sFieldValue = option.Value.ToString();
matchFound = true;
// We return the first match found
// Dynamics should make it impossible for there to be multiple matches,
// but, just in case, we are defaulting to this behavior.
// Changing the optionset value must be done with an int, it cannot cast a string to an int.
// This is the line that seems to cause the problem is defaulting to null in the picklist
// However, it is also the same line that updates the picklist
// I've confirmed we are not passing a bad value to SetOrAddAttribute
// Is there something about the way this works that I am not taking into account?
entity.SetOrAddAttribute(CrmFieldName, Int32.Parse(sFieldValue));
break;
}
}
if (!matchFound)
{
// Error Handling
}
}