Search code examples
dynamics-crmdynamics-crm-online

Adding DynamicPropertyInstance doesn't mark the SalesOrderDetail as valid


I have the following code:

var propertyInstance = new DynamicPropertyInstance()
{
    DynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, Guid.Parse("0ceedfcc-68b2-e711-8168-e0071b658ea1")),
    ValueString = jobId.ToString(),
    RegardingObjectId = line.ToEntityReference(),
};

crmContext.AddObject(dynamicPropertyInstance);
crmContext.SaveChanges();

It is successfully adding a DynamicPropertyInstance to a SalesOrderLine, but when viewing the Order in the CRM UI it does not pass the validation (as it is a required property). I've not managed to find a way to make this property valid. Editing the property that I've added in the UI (resetting the value) also fails to mark the instance as valid. Adding exactly the same property through the UI does mark it as valid.

The Id of the DynamicProperty is correct, as verified by loading the 2 instance records through the SDK and comparing the properties. Rather strangely, when I load the 2 records through the SDK the one I've created in code has a validationstatus of true (even though it's not) and the one that I've created in the UI has a validationstatus of false and ValueString returns null (which is wrong). All of the other properties either match or have relevant values (such as dates, object Ids etc)

I'm probably missing a method call to recalculate whether the instance is valid or not, but I can't find anything in the documentation to support that. Failing that, it's possibly a bug in CRM


Solution

  • Raised a case with Microsoft support, and was given some workaround code:

    //Get DynamicPropertyInstance
    
    UpdateProductPropertiesRequest UpdateRequest = new UpdateProductPropertiesRequest();
    UpdateRequest.PropertyInstanceList = new EntityCollection();
    UpdateRequest.PropertyInstanceList.EntityName = DynamicPropertyInstance.EntityLogicalName;
    Entity dpInstance = new Entity(DynamicPropertyInstance.EntityLogicalName, Dpi.Id);
    dpInstance.Attributes.Add(nameof(Dpi.ValueString).ToLower(), "Blarg");
    dpInstance.Attributes.Add(nameof(Dpi.DynamicPropertyInstanceid).ToLower(), Dpi.Id);
    dpInstance.Attributes.Add(nameof(Dpi.RegardingObjectId).ToLower(), new EntityReference(SalesOrderDetail.EntityLogicalName, line.Id));
    dpInstance.Attributes.Add(nameof(Dpi.DynamicPropertyId).ToLower(), new EntityReference(DynamicProperty.EntityLogicalName, dpId));
    
    UpdateRequest.PropertyInstanceList.Entities.Add(dpInstance);
    
    crmContext.Execute(UpdateRequest);
    

    Basically, it looks like you have to re-set or re-attach the entities for CRM to pick it up, so this is a workaround for a bug in CRM