Beispiel #1
0
        public async Task <IActionResult> PutPlayer([FromBody] PlayerListVm playerList)
        {
            // Final validation of request model
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var players = playerList.ConvertToListOfPlayerModels();

            foreach (Player p in players)
            {
                // Validate EF model
                TryValidateModel(p);
                if (!ModelState.IsValid)
                {
                    BadRequest(ModelState);
                }

                if (!PlayerExists(p.Id))
                {
                    return(NotFound($"Player Id: {p.Id} doesn't exist."));
                }
            }

            _context.Player.UpdateRange(players);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

            return(Ok(playerList));
        }
Beispiel #2
0
        public async Task <IActionResult> PostPlayer([FromBody] PlayerListVm playerList)
        {
            // Final validation of request model
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            foreach (PlayerVm p in playerList.Players)
            {
                TryValidateModel(p);
                if (!ModelState.IsValid)
                {
                    BadRequest(ModelState);
                }
            }

            var players = playerList.ConvertToListOfPlayerModels();

            _context.Player.AddRange(players);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException ex) when((ex.InnerException as SqlException)?.Number == 2627)
            {
                var message = SqlExceptionHandlers.DuplicatePrimaryKeyException(ex);

                return(BadRequest(message));
            }

            var ids = players.Select(p => p.Id).ToArray();

            return(CreatedAtAction("GetPlayer", new { id = ids }, playerList));
        }