private bool ValidateRentalDetails(BoatRental boatRental) { using (_dbContext) { var result = _dbContext.Boats.FirstOrDefault(x => x.Id == boatRental.BoatId); if (result == null) { throw new Exception("Boat ID does not exist"); } var availableToRent = _dbContext.BoatRentals.FirstOrDefault(x => x.BoatId == boatRental.BoatId && x.EndTime > boatRental.EndTime); if (availableToRent != null) { throw new Exception("Boat Id is not available for rent at this moment, it is already rented to other user"); } } if (string.IsNullOrWhiteSpace(boatRental.CustomerName)) { throw new Exception("Customer Name required"); } if (boatRental.EndTime <= boatRental.StartTime) { throw new Exception("End time can't be less than or equal to Start time"); } return(true); }
public async Task <BoatRental> RentBoat(int boatId, string customerName, DateTime From) { BoatRental boatRental = new BoatRental { BoatId = boatId, CustomerName = customerName, StartTime = From, EndTime = DateTime.MaxValue }; if (ValidateRentalDetails(boatRental)) { using (_dbContext) { await _dbContext.BoatRentals.AddAsync(boatRental); await _dbContext.SaveChangesAsync(); return(boatRental); } } return(null); }