public async Task <EventDto> UpdateEvent(int id, EventDto eventDto) { try { //This GetEventByIdAsync holds the Entity and untill it is finished, it can't be updated. //This is the reason we need to add AsNoTracking Event eventToUpdate = await _eventPersistence.GetEventByIdAsync(id); if (eventToUpdate == null) { return(null); } eventDto.Id = eventToUpdate.Id; //The Map takes all eventDto fields values and pass it to eventToUpdate _mapper.Map(eventDto, eventToUpdate); _generalPersistence.Update <Event>(eventToUpdate); if (await _generalPersistence.SaveChangesAsync()) { var eventToReturn = await _eventPersistence.GetEventByIdAsync(eventToUpdate.Id); //The event is returned just in case the dev wants to use it for something in project. return(_mapper.Map <EventDto>(eventToReturn)); } return(null); } catch (Exception ex) { throw new Exception($"Erro: {ex.Message}"); } }
public async Task <BatchDto[]> SaveBatch(int eventId, BatchDto[] models) { try { //Takes all batches from a given Event Batch[] batches = await _batchPersistence.GetAllBatchesByEventIdAsync(eventId); if (batches == null) { return(null); } foreach (BatchDto model in models) { if (model.Id < 1) { Batch batchToAdd = _mapper.Map <Batch>(model); batchToAdd.EventId = eventId; _generalPersistence.Add <Batch>(batchToAdd); await _generalPersistence.SaveChangesAsync(); } //If a batch (model) has an Id, it means that it will be updated, because already exists. else { //Takes the each batch from a given Event. Batch batch = batches.FirstOrDefault(b => b.Id == model.Id); model.EventId = eventId; //Pass to the batch the new values contained in the model. _mapper.Map(model, batch); //Updates it. _generalPersistence.Update <Batch>(batch); await _generalPersistence.SaveChangesAsync(); } } var batchReturn = await _batchPersistence.GetAllBatchesByEventIdAsync(eventId); return(_mapper.Map <BatchDto[]>(batchReturn)); } catch (Exception ex) { throw new Exception(ex.Message); } }