2

How can i implement PATCH HTTP method without using Entity framework in order to apply some partial update to a resource(s) ? i'm using dapper for my data access but i dont know how to implement PATCH only using Dapper

1 Answer 1

3

Adding JSON Patch To Your ASP.net Core Project

Step1. Install-Package Microsoft.AspNetCore.JsonPatch

Step2. implement HttpPatch action

[HttpPatch("update/{id}")]
public Person Patch(int id, [FromBody]JsonPatchDocument<Person> personPatch)
{
    Person person = _personRepository.GetById(id); // Get person object from the database via Dapper.
    
    personPatch.ApplyTo(person); //Apply the patch to that Entity. 
    
    _personRepository.Update(personDatabase); //Update your entity in the database via Dapper. 

    return personDatabase;
}

JsonPatch in ASP.NET Core web API

Simple example

  1. Get the entity from db _personRepository.GetById(id)

    { "id": 1, "name": "Michael" }

  2. Apply the patch to entity

    [ { "op": "replace", "path": "/name", "value": "Tony" } ]

    Get new entity

    { "id": 1, "name": "Tony" }

  3. Then update all fields of entity in _personRepository.Update(personDatabase).

Sign up to request clarification or add additional context in comments.

2 Comments

how would you implement "_personRepository.Update(personDatabase)" to only update fields that changed value ?
_personRepository.Update could update all fields. I posted a simple example for u to understand how it update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.