public async Task AddUnitAsync(int id, int quantity, int unitId) { int unitQuantity = 0; Country country = await _context.Countries .SingleAsync(m => m.Id == id); Unit unit = await _context.Units .SingleAsync(u => u.Id == unitId); var units = await _context.CountryUnits .Where(c => c.CountryId == id) .Where(u => u.UnitId == unitId) .FirstOrDefaultAsync(); if (quantity <= 0) { throw new GameException("Quantity", "Quantity cannot be null or negative"); } if (!IsFreeBarrackCapacity(country, quantity)) { throw new GameException("Quantity", "Not enough capacity in barracks!"); } if (unit.Price * quantity > country.Gold) { throw new GameException("Quantity", "Not enough Gold!"); } if (units == null) { CountryUnit countryUnit = new CountryUnit { CountryId = country.Id, Country = country, UnitId = unit.Id, Unit = unit, Count = quantity }; country.CountryUnits.Add(countryUnit); unitQuantity += quantity; country.Gold -= unit.Price * quantity; _context.Countries.Update(country); _context.CountryUnits.Add(countryUnit); } else { units.Count += quantity; country.Gold -= unit.Price * quantity; _context.Countries.Update(country); _context.CountryUnits.Update(units); } await _context.SaveChangesAsync(); }
private void AddCountryListIfNotExists(CountryUnit countryList) { if (_context.CountryUnit.Any(l => l.Description == countryList.Description)) { return; } _context.CountryUnit.Add(countryList); _context.SaveChanges(); }