Razor Page not showing foreign table data

119 Views Asked by At

I have a model class with two foreign keys and their respective navigation properties. However, when loading this model class, the foreign table data not showing.

Following is the class code:

public class SquadPlayer
{
    public int Id { get; set; }

    public int SquadId { get; set; }

    public int PlayerId { get; set; }

    public Squad Squad { get; set; }

    public Player Player { get; set; }
}

Back-end .cs code

public async Task OnGetAsync()
{
    SquadPlayer = await _context.SquadPlayers.ToListAsync();
}

Display .cshtml code

<td>
       @Html.DisplayFor(modelItem => item.Squad.Name)
</td>
<td>
       @Html.DisplayFor(modelItem => item.Player.Name)
</td>
1

There are 1 best solutions below

2
On BEST ANSWER

Update this code:

public async Task OnGetAsync()
{ 
    SquadPlayer = await _context.SquadPlayers.ToListAsync(); 
}

to:

public async Task OnGetAsync()
{ 
    SquadPlayer = await _context.SquadPlayers
                                .Include(x => x.Squad)
                                .Include(x => x.Player).ToListAsync(); 
}