public IHttpActionResult AddLocationToPlan(LocationInPlanViewModels planLocation) { try { PlanLocation location = ModelBuilder.ConvertToModels(planLocation); if (!planLocation.Index.HasValue) { Plan plan = _planService.Find(planLocation.PlanId, _ => _.PlanLocations, _ => _.Notes); IEnumerable <PlanLocation> planLocations = plan.PlanLocations; IEnumerable <Note> planNotes = plan.Notes; int maxLocationIndex = planLocations.OrderByDescending(_ => _.Index).FirstOrDefault() != null ? planLocations.OrderByDescending(_ => _.Index).FirstOrDefault().Index : 0; int maxPlanIndex = planNotes.OrderByDescending(_ => _.Index).FirstOrDefault() != null ? planNotes.OrderByDescending(_ => _.Index).FirstOrDefault().Index : 0; location.Index = (maxLocationIndex > maxPlanIndex ? maxLocationIndex : maxPlanIndex) + 1; } //end if identity max index bool result = _planService.AddLocationToPlan(location); if (result) { return(Ok()); } return(BadRequest()); } catch (Exception ex) { _loggingService.Write(GetType().Name, nameof(AddLocationToPlan), ex); return(InternalServerError(ex)); } }