-1

I saw this How to include a child object's child object in Entity Framework 5

However, I'm using MVC 5 and that doesn't seem to be working.

I have a typical Tournament, Games, Teams structure, and am trying to include Teams when I query the tournament.

I am trying to run

db.Tournaments.Include(t => t.Games.Select(g => g.Team1)).ToList();

However Team1 is coming back null. Here are my classes:

public class Tournament
{
    public int TournamentId { get; set; }
    public string Name { get; set; }
    public virtual List<Game> Games { get; set; }
    public virtual List<Standing> Standings { get; set; }
}

public class Game
{
    public int GameId { get; set; }
    public Location Location { get; set; }
    public int LocationId { get; set; }
    public virtual Team Team1 { get; set; }
    public int Team1Id { get; set; }
    public virtual Team Team2 { get; set; }
    public int Team2Id { get; set; }
    public int Team1Score { get; set; }
    public int Team2Score { get; set; }
    public DateTime Time { get; set; }
    public Tournament Tournament { get; set; }
    public int TournamentId { get; set; }
}

public class Team
{
    public int TeamId { get; set; }
    public string Name { get; set; }
    public string Coach { get; set; }
}

Does anyone have any suggestions?

Community
  • 1
  • 1
bak
  • 206
  • 2
  • 9

2 Answers2

0

You are trying to load a single cell from the Games table in the Db, I don't think you can do this the way you are trying too.

You have your Navigation properties set to Virtual, so you should lazy load automatically when you call the property that you need. There is no need for an include statement.

All you normally need to do is iterate through the list of games in tournaments

    var Tournaments = Db.Tournaments.ToList();

        foreach (var game in Tournaments.Games)
        {
            game.Team1.TeamId;
            game.Team1.Coach;
            game.Team1.Name;
        }
Vahx
  • 626
  • 10
  • 23
0
db.Tournaments.Include(t => t.Games.Team1).ToList();

This is the correct way of Including single child entities in EF5.

Okan Aslankan
  • 3,016
  • 2
  • 21
  • 26