public IHttpActionResult PutDefault([FromUri] int id, [FromBody] UpdateAutopilotSettingsModel command) { if (command != null && id != command.Id) { ModelState.AddModelError(nameof(UpdateAutopilotSettingsModel.Id), "Model id does not match"); return(BadRequest(ModelState)); } var autopilotSettings = _autopilotSettingsRepository.Get(id); if (autopilotSettings == null) { return(NotFound()); } if (!_autopilotSettingsValidator.IsValid(command)) { return(_autopilotSettingsValidator.BadRequest()); } autopilotSettings.DefaultFlexibilityLevelId = command.DefaultFlexibilityLevelId; autopilotSettings.ScenariosToGenerate = command.ScenariosToGenerate; _autopilotSettingsRepository.Update(autopilotSettings); UpdateAutopilotRulesRepository(command.AutopilotRules); // Do not remove this, need to persist changes now so that we can return AutopilotSettingsModel _autopilotSettingsRepository.SaveChanges(); _autopilotRuleRepository.SaveChanges(); return(Ok(Mappings.MapToAutopilotSettingsModel(autopilotSettings, _autopilotRuleRepository, _ruleRepository, _ruleTypeRepository, _mapper))); }
/// <summary> /// Updates autopilot rules according to the rules repository changes /// </summary> /// <param name="ruleTypeId"></param> /// <param name="newRules"></param> /// <param name="deletedRules"></param> private void UpdateAutopilotRulesRepository(int ruleTypeId, IReadOnlyCollection <int> newRules, IReadOnlyCollection <int> deletedRules) { var flexibilityLevels = _flexibilityLevelRepository.GetAll().ToList(); // delete autopilot rules if (deletedRules != null && deletedRules.Any()) { var autopilotRulesToDelete = _autopilotRuleRepository.GetAll() .Where(rt => rt.RuleTypeId == ruleTypeId && deletedRules.Contains(rt.RuleId)).ToList(); if (autopilotRulesToDelete.Any()) { _autopilotRuleRepository.Delete(autopilotRulesToDelete.Select(r => r.Id)); } } // add new autopilot rules if (newRules != null && newRules.Any()) { foreach (var ruleId in newRules) { foreach (var flexibilityLevel in flexibilityLevels) { var autopilotRule = AutopilotRule.Create(flexibilityLevel.Id, ruleId, ruleTypeId); _autopilotRuleRepository.Add(autopilotRule); } } } _autopilotRuleRepository.SaveChanges(); }