Home > front end >  POST Request is Successful but GET Request is Null
POST Request is Successful but GET Request is Null

Time:09-20

I have a model called Players that is used within another model called Teams. After POSTing, the GET Request shows that the players data within teams comes back null whereas everything else returns as expected. See my code below.

Player model:

    public class Player
    {
        public long Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Teams Model:

    public class Team
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public IList<Player> Players { get; set; }
    }

Teams GET Request:

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Team>>> GetTeams()
        {
            return await _context.Teams.ToListAsync();
        }

Teams POST Request:

        [HttpPost]
        public async Task<ActionResult<Team>> PostTeam(Team team)
        {
            _context.Teams.Add(team);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetTeam), new { id = team.Id }, team);
        }

POST Request JSON on Swagger (FYI this posts successful):

{
  "id": 1,
  "name": "team name",
  "location": "team location",
  "players": [
    {
      "id": 1,
      "firstName": "firstName",
      "lastName": "lastName"
    }
  ]
}

The Teams GET Request Returned JSON:

[
  {
    "id": 1,
    "name": "string",
    "location": "string",
    "players": null
  }
]

How do I get the "players" data to return the inputted data as expected?

CodePudding user response:

Try to use explicit loading to load your players collection:

foreach(var team in teams) 
{
    var players = context.Entry(team)
        .Collection(b => b.Players)
        .Query();
}

Or eager loading:

await _context.Teams.Include(t => t.Players).ToListAsync();

Also you can be interested to Loading Related Data article by Microsoft to find out more about loading related entities.

  • Related