Guys consider the following problem we have supporting patch in our Microservice. We currently have nested models like this:
TopModel
{
Model Model1 {get; set;}
}
Model
{
SomeData Data1 {get; set;}
}
If I want to patch Data1 and the Model1 object already exists I would send the following patch command:
{
"value": { {somedata} },
"path": "topmodel/model1/data1",
"op": "add"
}
And call this:
jsonPatchDoc.ApplyTo(patchedModel);
This is fine and works. An issue arises when callers want to make the same call into an object whereby Model1 has previously not been instantiated and is therefore null. You get this error:
"For operation 'add', the target location specified by path 'topmodel/model1/data1' was not found."
To rectify this issue we can instantiate Model1 when retrieving it (before patching) like this:
if (topModel.Model1 == null)
topModel.Model1 = new Model();
Unfortunately when dealing with complex models many levels deep this manual instantiation becomes cumbersome and a significant overhead to maintain. We cannot instantiate these properties in the constructors of their owner classes because in many use cases they do need to be null (for example they should not be returned at all when not explicitly set).
So is there a way when using JsonPatchDocument to create Model1 dynamically if it is null and you are trying to patch one of its properties?