My HTTP requests cannot successfully add new players to my team within my code. Say I do a POST Request and add a team and a list of players within it. I then would try either a POST or a PATCH Request to add a new player to my team but it fails. My code is below:
public class Team
{
public long Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public IList<Player> Players { get; set; } = new List<Player>();
}
public class Player
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
[HttpPatch]
public async Task<ActionResult<Team>> AddPlayerToTeam(long id, List<Player> player)
{
var teams = await _context.Teams.Include(t => t.Players).ToListAsync();
var team = (from selectedTeam in teams where selectedTeam.Id == id select
selectedTeam).SingleOrDefault();
if (id != team.Id)
{
return BadRequest();
}
team.Players.Clear();
team.Players = player
_context.Update(team);
await _context.SaveChangesAsync();
return NoContent();
}
[HttpPut("{id}")]
public async Task<IActionResult> PutTeam(long id, Team team)
{
if (id != team.Id)
{
return BadRequest();
}
_context.Teams.Update(team);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TeamExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
How can I add more Players to my team.Players?