My starting solution is to add an extension method for ModelStateDictionary
that looks like this
public static void ApplyPatchDocument<T>(this ModelStateDictionary modelState, JsonPatchDocument<T> patchDoc) where T : class
{
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
if (patchDoc == null)
{
throw new ArgumentNullException(nameof(patchDoc));
}
var modelStateKeys = modelState.Keys.ToList();
for (var i = modelStateKeys.Count - 1; i >= 0; i--)
{
var modelStateKey = modelStateKeys[i];
var modelStateEntry = modelState[modelStateKey];
if (modelStateEntry.Errors.Count > 0
&& !patchDoc.Operations
.Any(op => op.path
.TrimStart('/')
.Replace('/', '.')
.IndexOf(modelStateKey, StringComparison.OrdinalIgnoreCase) > -1))
{
modelState.Remove(modelStateKey);
}
}
}
There are issues with this method, for example when you want to change an array property this won't work as it is but it's a good start. Hopefully it helps someone! :)