Exemplo n.º 1
0
        public async Task <Plant> Update(UpdatePlantModel model)
        {
            Plant plant = await _database.Plants
                          .Include(x => x.Field)
                          .FirstOrDefaultAsync(x => x.Id == model.Id);

            if (plant is null)
            {
                return(null);
            }

            Field field = await _database.Fields
                          .Include(x => x.Plants)
                          .FirstOrDefaultAsync(x => x.Id == model.FieldId);

            if (field is null)
            {
                throw new FieldNotFoundException(model.FieldId);
            }

            if (field.Plants.Any(x => (x.Row == model.Row) && (x.Column == model.Column) && (x.Id != model.Id)))
            {
                throw new PlantExistsAtCoordinatesException(model.Row, model.Column);
            }

            Domain.Species species = await _database.Species.FirstOrDefaultAsync(x => x.Id == model.SpeciesId);

            if (species is null)
            {
                throw new SpeciesNotFoundException(model.SpeciesId);
            }

            _mapper.Map(model, plant);
            plant.ChangeField(field);
            plant.Species = species;
            _database.Plants.Update(plant);
            await _database.SaveAsync();

            return(plant);
        }