Querying EF Core one-to-many and further one-to-many relationship

asp.net-core ef-core-2.1 entity-framework-core

Question

I have 3 models, Competition, Team and TeamUser. Each Competition has many teams and each team has many users. I want to use EF Core to bind all 3 together when returning the data to the view, but I can't really bind to users. Thus I have to implement some complex logic at my view which although it works, looks super messy and confusing. I'm sure there's a way to return the data together.

Competition model class:

public class Competition
{
    [Key]
    public int ID { get; set; }
    [Required]
    [Display(Name = "Competition Name")]
    public string CompetitionName { get; set; }
    [Required]
    public string Status { get; set; }

    public ICollection<Team> Teams { get; set; }
}   

Team model class:

public class Team
{
    [Key]
    public int TeamID { get; set; }

    [Required]
    [DisplayName("Team Name")]
    public string TeamName { get; set; }

    [ForeignKey("CompetitionID")]
    public int CompetitionID { get; set; }

    public ICollection<TeamUser> TeamUsers { get; set; }

}

TeamUser model class:

public class TeamUser
{
    [Key]
    public int TeamUserID { get; set; }

    [ForeignKey("TeamId")]
    public int TeamId { get; set; }
    public string UserId { get; set; }
}

This is my controller.

public IActionResult Index()
{
     var competition = _context.Competitions
         .Include(c => c.Teams)
         .ToList();

     var teamUsers = _context.TeamUsers
         .ToList();

     if (competition == null)
     {
         return NotFound();
     }

     CompetitionIndexViewModel vm = new CompetitionIndexViewModel();
     vm.Competition = competition;
     vm.TeamUsers = teamUsers;

     return View(vm);
}

As you can see it is very messy and I have to resort to using viewmodel to get my data over. Hope there is a simpler solution. Thank you very much!

1
1
1/13/2019 1:56:18 PM

Accepted Answer

You don't need to use CompetitionIndexViewModel. Just write your query as follows and pass the List<Competition> to the View.

public IActionResult Index()
{
     List<Competition> competitions = _context.Competitions
         .Include(c => c.Teams).ThenInclude(t => t.TeamUsers)
         .ToList();

     return View(competitions);
}

Now in the view each Competition should have a list of Teams and each Team should have a list of TeamUsers.

2
1/13/2019 1:43:05 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow