public async Task <ActionResult <CampaignEntityDTO> > Post(CampaignEntityDTO entity) { var faction = (await _context.Locations.Include(p => p.Faction).FirstOrDefaultAsync(p => p.Id == entity.LocationId)).Faction; var _entity = new CampaignEntity { Campaign = await _context.Campaigns.FirstOrDefaultAsync(p => p.Id == entity.CampaignId), Entity = await _context.Entities.FirstOrDefaultAsync(p => p.Id == entity.EntityId), Faction = faction, Location = await _context.Locations.FirstOrDefaultAsync(p => p.Id == entity.LocationId), AvailableAt = (await _context.Campaigns.FirstOrDefaultAsync(p => p.Id == entity.CampaignId)).StartDate, Count = entity.Count, Status = entity.Status }; var unitCost = (await _context.CampaignEntityCosts .Include(p => p.Campaign) .Include(p => p.Entity) .FirstOrDefaultAsync(p => p.Entity.Id == entity.EntityId && p.Campaign.Id == entity.CampaignId))?.Cost ?? (await _context.Entities.FirstOrDefaultAsync(p => p.Id == entity.EntityId)).DefaultCost; if (unitCost * entity.Count > faction.Budget) { return(BadRequest()); } faction.Budget -= unitCost * entity.Count; await _context.CampaignEntities.AddAsync(_entity); _context.Factions.Update(faction); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(Get), new { id = _entity.Id }, entity)); }
public async Task <IActionResult> Put(int id, CampaignEntityDTO entity) { if (id != entity.Id) { return(BadRequest()); } var _entity = await _context.CampaignEntities .Include(p => p.Campaign) .Include(p => p.Entity) .Include(p => p.Location) .Include(p => p.Faction) .FirstOrDefaultAsync(p => p.Id == id); _entity.Campaign = await _context.Campaigns.FirstOrDefaultAsync(p => p.Id == entity.CampaignId); _entity.Entity = await _context.Entities.FirstOrDefaultAsync(p => p.Id == entity.EntityId); _entity.Faction = (await _context.Locations.Include(p => p.Faction).FirstOrDefaultAsync(p => p.Id == entity.LocationId)).Faction; _entity.Location = await _context.Locations.FirstOrDefaultAsync(p => p.Id == entity.LocationId); _entity.AvailableAt = (await _context.Campaigns.FirstOrDefaultAsync(p => p.Id == entity.CampaignId)).StartDate; _entity.Count = entity.Count; _entity.Status = entity.Status; _context.CampaignEntities.Update(_entity); await _context.SaveChangesAsync(); return(NoContent()); }