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!
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
.