public async Task BuyUnits(int userId, SquadUnitListDto squadUnitListDto) { var player = await _dbContext.Players .Include(p => p.Stock) .Include(p => p.City) .ThenInclude(c => c.CityBuildings) .ThenInclude(cb => cb.Building) .Include(p => p.Army) .ThenInclude(a => a.Squads) .ThenInclude(s => s.SquadUnits) .ThenInclude(su => su.Unit) .Where(p => p.UserId == userId) .SingleOrDefaultAsync(); var defendingSquad = player.Army.Squads .Where(s => s.CityId == player.City.Id) .SingleOrDefault(); // COUNT A FEW VALUES FOR CHECKINGS var sumPearlAmount = 0; foreach (var squadUnit in squadUnitListDto.SquadUnits) // count pearl needed to buy the requested units { sumPearlAmount += await _squadService.GetSumSquadUnitPrice(squadUnit.Name, squadUnit.NumberOfUnits); } var sumBeds = 0; foreach (CityBuilding cityBuilding in player.City.CityBuildings) //count sum beds { sumBeds += cityBuilding.NumberOfBuildings * cityBuilding.Building.SoldierUnitNumber; } var squadUnits = await _squadService.GetAllSquadUnitByPlayerId(player.Id); var sumOccupiedBeds = squadUnits.Sum(su => su.NumberOfUnits); //count occupied beds var numberOfUnitsToBeHired = squadUnitListDto.SquadUnits.Sum(su => su.NumberOfUnits); // count number of units to be hired // CHECKINGS if (sumBeds < sumOccupiedBeds + numberOfUnitsToBeHired) { throw new GeneralGameException($"Nem tudsz {sumOccupiedBeds + numberOfUnitsToBeHired} egységet elszállásolni, csak {sumBeds} szállás helyed van!"); } else if (player.Stock.PearlAmount < sumPearlAmount) { throw new GeneralGameException("Nincs elég gyöngyöd, hogy megvedd ezeket az egységeket!"); } else { await _stockService.ReducePearl(player.Stock, sumPearlAmount); } foreach (var squadUnit in squadUnitListDto.SquadUnits) { var originalSquadUnit = defendingSquad.SquadUnits.Where(su => su.Unit.Type == squadUnit.Name).SingleOrDefault(); if (originalSquadUnit == null) { await _squadService.InsertUnitType(defendingSquad, squadUnit.Name, squadUnit.NumberOfUnits); } else { await _squadService.UpdateUnitTypeNumber(defendingSquad, squadUnit.Name, originalSquadUnit.NumberOfUnits + squadUnit.NumberOfUnits); } } }