Search code examples
c#asp.net-mvcentity-framework-6one-to-manyscaffolding

How to show the many side in a one-to-many relation as a table using Entity Framework scaffolding


After choose a team I need to show the players in this team.

I think the better way is to show a table of players in the create/edit/show team views.

This is my model:

public class Player
{
    [Key]
    public int PlayerId { get; set; }
    [Required]
    [Display(Name = "Name", AutoGenerateField = false)]
    public string name { get; set; }
    public int TeamId { get; set; }
    [Display(Name = "Team", AutoGenerateField = false)]
    public virtual Team Team { get; set; }
}

public class Team
{
    [Key]
    public int TeamId { get; set; }
    [Required]
    [Display(Name = "Name", AutoGenerateField = false)]
    public string name { get; set; }
    [Display(Name = "Players")]
    public virtual ICollection<Player> Players { get; set; }
}

But entity framework scaffold does not create a table inside teams views. It just create a combobox to choose the team in the player views.

I searched on the internet but not found anything about that. How could I force scaffold to generate this table? Or it is necessary to create this table manually?

I'm using Visual Studio 2015 and Entity Framework 6+ and C# in a asp.net mvc project.

What I what to show is something like this:

Team

Name: Survivors

Players

 _________
| Name  v 
 _________
| Bill    
| Louis   
| Zoey    
| Francis 
 _________

Solution

  • I was able to show the table by editing my Team view manually. Just added that:

     <table class="table">
        <tr>
            <th>
                Name
            </th>
            <th></th>
        </tr>
    
    
        @foreach (var player in Team.Players)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => player.name)
                </td>
                <td>
                    @Html.ActionLink("Create New", "Create", "Players") |
                    @Html.ActionLink("Edit", "Edit", new  { controller = "Players", id = player.PlayerId }) |
                    @Html.ActionLink("Details", "Details", new  { controller = "Players", id = player.PlayerId }) |
                    @Html.ActionLink("Delete", "Delete", new  { controller = "Players", id = player.PlayerId })
                </td>
            </tr>
        }
    
    </table>
    

    Not the easyest way, but works.