Skip to content

Instantly share code, notes, and snippets.

@zielinski-piotr
Created September 14, 2021 21:00
Show Gist options
  • Save zielinski-piotr/e917dc4a24da3e4db2bf89c298d61e0c to your computer and use it in GitHub Desktop.
Save zielinski-piotr/e917dc4a24da3e4db2bf89c298d61e0c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using JSONPatchTutorial.Contract.Requests;
using JSONPatchTutorial.Data;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.EntityFrameworkCore;
using DataModelHouse = JSONPatchTutorial.Domain.House;
namespace JSONPatchTutorial.Service
{
public class HouseService : IHouseService
{
private readonly IRepository _repository;
private readonly IMapper _mapper;
public HouseService(IRepository repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task UpdateHouse(JsonPatchDocument<House.Patch> patch, Guid id)
{
_ = id == Guid.Empty ? throw new ArgumentException(nameof(id)) : id;
_ = patch ?? throw new ArgumentNullException(nameof(patch));
var dataModelHouse = await _repository.Get<DataModelHouse>()
.Include(x => x.Address)
.FirstOrDefaultAsync(x => x.Id == id) ??
throw new KeyNotFoundException($"There is no {nameof(House)} with Id: {id}");
var apiModelHouse = _mapper.Map<House.Patch>(dataModelHouse);
patch.ApplyTo(apiModelHouse);
_mapper.Map(apiModelHouse, dataModelHouse);
_repository.Update(dataModelHouse);
await _repository.SaveChangesAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment