PATCH when working with DTO c# entity-framework-core json-patch rest


I'm working on core webAPi and EF core, and want to implement "update" operation (partially edit entity). I searched the correct way to deal with that, and saw that I should use jsonPatch. the problem is that I'm expose just DTOs through my API, and if I use jsonPatch like:

public AccountDto Patch(int id, [FromBody]JsonPatchDocument<AccountDto> patch)

then I need to apply the patch on DTO, and I can't apply it on the model entity, without create a new entity.

I also read about Odata.Delta, but it still not work on core, and furthermore - I don't think it has a built in solution for working with dto (I found this example that can help when Odata for core will be available)

So, for now - should I use POST and send DTO with list of changed properties in query (as I saw here), Or - there is more elegant solution?


5/23/2017 11:46:01 AM

Accepted Answer

Now I saw that using autoMapper I can do just

CreateMap<JsonPatchDocument<AccountDTO>, JsonPatchDocument<Account>>();
        CreateMap<Operation<AccountDTO>, Operation<Account>>();

and it work like a charm :)

7/31/2016 7:02:12 PM

Popular Answer


I just remove the type from JsonPatchDocument, and saw that it can work without type...

    public AccountDTO Patch(int id, [FromBody]JsonPatchDocument patch)
        return _mapper.Map<AccountDTO>(_accountBlService.EditAccount(id, patch));

And then, In BL layer,

public Account EditAccount(int id, JsonPatchDocument patch)
        var account = _context.Accounts.Single(a => a.AccountId == id);
        var uneditablePaths = new List<string> { "/accountId" };

        if (patch.Operations.Any(operation => uneditablePaths.Contains(operation.path)))
            throw new UnauthorizedAccessException();
        return account;

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow