/// <summary> /// Creates a new location object for a specific /// animal and stores it in the database. /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task CreateLocation(LocationBm model) { var animalLocation = await context.Locations.FirstOrDefaultAsync(x => x.AnimalId == model.AnimalId); if (animalLocation == null) { var location = mapper.Map <Location>(model); context.Locations.Add(location); await context.SaveChangesAsync(); logger.LogInfo($"Location for animal {model.AnimalId} successfully added."); } else { throw new BadRequestException($"Animal with id {model.AnimalId} already has a location."); } }
/// <summary> /// Creates a new animal and stores it in the database. In addition /// it finds current user and stores the current user as the animal's creator. /// </summary> /// <param name="model"></param> /// <returns>animal's id</returns> public async Task <int> CreateAnimal(AnimalBm model) { var animal = mapper.Map <Animal>(model); var userId = GetCurrentUser(); animal.UserId = userId; // will be better to put in constructor of DTO or Bm animal.CreatedAt = DateTime.Now; animal.UpdatedAt = DateTime.Now; var userAnimals = await context.Animals.Where(x => x.UserId == userId) .FirstOrDefaultAsync(x => x.Name == model.Name); if (userAnimals == null) { context.Add(animal); await context.SaveChangesAsync(); var animalLocation = mapper.Map <LocationBm>(model); animalLocation.AnimalId = animal.Id; await locationRepository.CreateLocation(animalLocation); logger.LogInfo($"Animal with id {animal.Id} successfully created."); return(animal.Id); } else { throw new BadRequestException($"You already registered an animal with the same name."); } }