public ActionResult <EditChecklistItemRequest> EditById(Guid id) { var checklistItem = _checklistItemRepository.GetById(id); if (checklistItem == null) { return(NotFound()); } else { var tags = _tagRepository.GetAll().ToList(); var selectedTagIds = checklistItem.ChecklistItemTags.Select(cit => cit.TagId); var viewModel = new EditChecklistItemRequest { ChecklistItem = Mapper.Map <Models.Web.Checklists.ChecklistItem>(checklistItem), Tags = Mapper.Map <IList <Tag> >(tags), SelectedTagIds = selectedTagIds }; return(Json(viewModel)); } }
public ActionResult Update(Guid id, [FromBody] EditChecklistItemRequest request) { // TODO Determine if Find() will help with getting rid of context attach. var checklistItemInDb = _context.ChecklistItems .Include(ci => ci.ChecklistItemTags) .ThenInclude(cit => cit.Tag) .Include(ci => ci.CannedResponses) .Include(ci => ci.Measurements) .SingleOrDefault(ci => ci.Id == id); if (checklistItemInDb == null) { return(NotFound()); } // Duplicating database entries bug - MUST BE DONE BEFORE PROP CHANGES // http://stackoverflow.com/a/22389505/2831961 foreach (var measurement in checklistItemInDb.Measurements) { _context.Measurements.Attach(measurement); } foreach (var cannedResponse in checklistItemInDb.CannedResponses) { _context.CannedResponses.Attach(cannedResponse); } var tags = checklistItemInDb.ChecklistItemTags?.Select(joinItem => joinItem.Tag); if (tags != null) { foreach (var tag in tags) { _context.Tags.Attach(tag); } } foreach (var measurementInVm in request.ChecklistItem.Measurements) { var measurementInDb = checklistItemInDb.Measurements.SingleOrDefault(cm => cm.Id == measurementInVm.Id); if (measurementInDb != null) { measurementInDb.Label = measurementInVm.Label; measurementInDb.Unit = measurementInVm.Unit; measurementInDb.MinValue = measurementInVm.MinValue; measurementInDb.MaxValue = measurementInVm.MaxValue; measurementInDb.StepSize = measurementInVm.StepSize; } } foreach (var cannedResponseInVm in request.ChecklistItem.CannedResponses) { var cannedResponseInDb = checklistItemInDb.CannedResponses.SingleOrDefault(cr => cr.Id == cannedResponseInVm.Id); if (cannedResponseInDb != null) { cannedResponseInDb.Response = cannedResponseInVm.Response; cannedResponseInDb.LevelsOfConcern = (IList <InspectionItemCondition>)cannedResponseInVm.LevelsOfConcern.Select(condition => TypeSafeEnum.FromValue <InspectionItemCondition>((int)condition)); cannedResponseInDb.Url = cannedResponseInVm.Url; cannedResponseInDb.Description = cannedResponseInVm.Description; } } checklistItemInDb.Name = request.ChecklistItem.Name; checklistItemInDb.ChecklistItemTags = _context.Tags .Where(t => request.SelectedTagIds.Contains(t.Id)) .Select(t => new ChecklistItemTag { ChecklistItem = checklistItemInDb, ChecklistItemId = checklistItemInDb.Id, Tag = t, TagId = t.Id }) .ToList(); _context.SaveChanges(); return(NoContent()); }