Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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