public async Task <IActionResult> UpdateTrainingContent(long id, [FromBody] TrainingContentRequest request) { var trainingContent = await _context.TrainingContents .Where(p => p.Id == id) .Include(p => p.Trainings) .FirstOrDefaultAsync(); if (trainingContent == null) { return(NotFound("Content wasn't found")); } //training_content.Title = request.Title; //training_content.CategoryId = request.CategoryId; //training_content.coverImage = request.coverImage; //training_content.Author = request.Author; //trainingContent.Trainings = request.Trainings; _context.Entry(trainingContent).CurrentValues.SetValues(request); //delete existing trainingQuetions and answers foreach (var traing in trainingContent.Trainings.ToList()) { var item = await _context.Trainings.FindAsync(traing.Id); _context.Remove(item); await _context.SaveChangesAsync(); } //trainingContent.Trainings = request.Trainings; //update trainingQuetions and answers foreach (var requestTraingQuest in request.Trainings) { var trainingQuestions = await _context.Trainings .Where(c => c.TrainingContentId == trainingContent.Id) .Include(c => c.Answers) .FirstOrDefaultAsync(); if (trainingQuestions != null) { _context.Entry(trainingQuestions).CurrentValues.SetValues(requestTraingQuest); } else { var newtraining = new Training { Questions = requestTraingQuest.Questions, Answers = requestTraingQuest.Answers }; trainingContent.Trainings.Add(newtraining); } } //_context.TrainingContents.Update(trainingContent); await _context.SaveChangesAsync(); return(Ok(await _context.TrainingContents.ProjectTo <TrainingContentResponse>(_mapper.ConfigurationProvider) .FirstOrDefaultAsync(x => x.Id == trainingContent.Id))); }
public async Task <IActionResult> CreateTraining([FromBody] TrainingContentRequest request) { var res = await _context.TrainingContents .AddAsync(_mapper.Map <TrainingContent>(request)); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(CreateTraining), await _context.TrainingContents.ProjectTo <TrainingContentResponse>(_mapper.ConfigurationProvider) .ToListAsync())); }