public IActionResult Assign(GarageAssignmentViewModel gavm) { try { if (ModelState.IsValid) { if (gavm.GarageAssignment.Id == 0) { _unitOfWork.GarageAssignment.Add(gavm.GarageAssignment); } else { _unitOfWork.GarageAssignment.Update(gavm.GarageAssignment); } _unitOfWork.Save(); return(RedirectToAction(nameof(Index))); } } catch (Exception ex) { var evm = new ErrorViewModel { ErrorMessage = ex.Message.ToString() }; return(View("Error", evm)); } return(View(gavm)); }
//Assign bus to a garage public IActionResult Assign(int?id) { GarageAssignmentViewModel gavm = new GarageAssignmentViewModel() { GarageAssignment = new GarageAssignment(), GarageList = _unitOfWork.Garage.GetAll().Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }), BusList = _unitOfWork.Bus.GetAll().Select(i => new SelectListItem { Text = i.RegistrationNumber, Value = i.Id.ToString() }) }; try { if (id == null) { return(View(gavm)); } gavm.GarageAssignment.BusId = id.GetValueOrDefault(); gavm.GarageAssignment.Bus = _unitOfWork.Bus.Get(id.GetValueOrDefault()); //Check if the bus is parked in any garage var assignedGarage = _unitOfWork.GarageAssignment.GetFirstOrDefault(u => u.BusId == id && u.CheckOut == null, includeProperties: "Garage,Bus"); if (assignedGarage != null) { gavm.GarageAssignment.GarageId = assignedGarage.GarageId; gavm.GarageAssignment.Garage = assignedGarage.Garage; gavm.GarageAssignment.CheckIn = assignedGarage.CheckIn; } if (gavm.GarageAssignment.Bus == null) { throw new Exception("Unable to find the garage assignment for the bus"); } } catch (Exception ex) { var evm = new ErrorViewModel { ErrorMessage = ex.Message.ToString() }; return(View("Error", evm)); } return(View(gavm)); }