yasseros
yasseros

Reputation: 939

how to implement PATCH HTTP Method without using EF

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

Upvotes: 2

Views: 1622

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

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).

Upvotes: 3

Related Questions