I have the following method in my ASP.NET Core Web API. It's using Microsoft.AspNetCore.JsonPatch for patching:
[HttpPatch]
public IActionResult PatchCustomer([FromBody] JsonPatchDocument<CustomerModel> patchDoc)
{
if (patchDoc != null)
{
var customerEntity = _dbContext.Customers.Where(x=>x.CustomerID == id);
// the ApplyTo() method below throws compilation error because of type mismatch
patchDoc.ApplyTo(customerEntity, ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok();
}
else
{
return BadRequest(ModelState);
}
}
I could fix the error by changing the method parameter to type JsonPatchDocument<Customer> where Customer in an entity. However, I don't want to expose entity to the API method. The CustomerModel type has only certain properties that caller can update so it make sense to use CustomerModel as parameter to minimize the risk of caller accidentally updating some other property.
How to update Customer entity based on JsonPatchDocument here?
You can try to use
Automapperto mapCustomerModelto theCustomerentity, and then applyJsonPatchDocument.Or use Linq to query to map the attributes of theCustomerentity to the attributes of theCustomerModelmodel object. Then applyJsonPatchDocumenttoCustomerModel, and update the modified attribute value to the physical object. You can refer to the following examples:My Customer:
My CusterModel:
My method (useAutomapper):
The entity that needs to be mapped:
In program.cs:
Use Linq query(It should be noted that this method requires the attribute name and the type completely matching):