public bool UpdateCarWithId(int id, EditCarReturnViewModel editCarReturn) { if (CarExists(id)) { //First we deal with colors _colorService.EditColor(editCarReturn, id); //Then we deal with the car Car carToUpdate = _ctx.Cars.Where(c => c.CarId == id).Select(c => new Car { Amount = editCarReturn.Amount, Available = editCarReturn.Available, CarId = id, DefectDescription = editCarReturn.DefectDescription, HasDefect = editCarReturn.HasDefect, InspectionInProgress = c.InspectionInProgress, ModelNumber = editCarReturn.ModelNumber }).SingleOrDefault(); try { _ctx.Cars.Update(carToUpdate); _ctx.SaveChanges(); return(true); } catch { return(false); } } return(false); }
public ActionResult Edit(int id, EditCarReturnViewModel editCarReturn) { if (ModelState.IsValid) { try { bool updated = _carService.UpdateCarWithId(id, editCarReturn); if (updated) { return(RedirectToAction(nameof(Index))); } } catch { return(View("Error", new ErrorViewModel { RequestId = "There was an error" })); } } return(View()); }
public void EditColor(EditCarReturnViewModel editCarReturn, int carId) { List <Color> colorsToAdd = new List <Color>(); List <Color> colorsToUpdate = new List <Color>(); List <Color> colorsToDelete = new List <Color>(); if (editCarReturn.ColorIds != null) { for (int i = 0; i < editCarReturn.ColorIds.Count; i++) { if (ColorExists(editCarReturn.ColorIds[i])) { if (editCarReturn.OriginalColorNames[i] != editCarReturn.NewColors[i]) { if (string.IsNullOrEmpty(editCarReturn.NewColors[i])) { colorsToDelete.Add(new Color { CarId = carId, ColorId = editCarReturn.ColorIds[i], ColorName = editCarReturn.OriginalColorNames[i] }); } else { colorsToUpdate.Add(new Color { CarId = carId, ColorId = editCarReturn.ColorIds[i], ColorName = editCarReturn.NewColors[i] }); } } } } } if (editCarReturn.Colors != null) { foreach (string color in editCarReturn.Colors) { if (!string.IsNullOrEmpty(color)) { colorsToAdd.Add(new Color { CarId = carId, ColorName = color }); } } } if (colorsToDelete.Count > 0) { try { _ctx.Colors.RemoveRange(colorsToDelete); } catch { } } if (colorsToUpdate.Count > 0) { try { _ctx.Colors.UpdateRange(colorsToUpdate); } catch { } } if (colorsToAdd.Count > 0) { try { _ctx.Colors.AddRange(colorsToAdd); _ctx.SaveChanges(); } catch { } } }