Reputation: 2655
I'm a bit new to the MVC approach. I have started with the database model first. I currently have two tables:
Fixtures (amongst other fields) has a FK link to the team table for home and away team.
public class Team
{
public virtual int TeamId { get; set; }
public virtual string Name { get; set; }
public virtual int DivisionId { get; set; }
}
public class Fixture
{
public int FixtureId { get; set; }
public DateTime Date { get; set; }
public Team HomeTeam { get; set; }
public Team AwayTeam { get; set; }
}
I notice when this comes through to the FixtureController both the HomeTeam and AwayTeam objects are null. Do I have to somehow wire this inside the controller or should it automatically make the connection?
So ideally then in the view I can have:
<td>
@Html.DisplayFor(modelItem => item.HomeTeam.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.AwayTeam.Name)
</td>
So I suppose my question is how do I get my controller to make the link from Fixtures->Team?
Thanks
Upvotes: 2
Views: 1188
Reputation: 14409
In your controller, use .Include
to get the data. See also: Loading Related Objects
var fixtures = db.Fixtures // The fixture data
.Include(fixture => fixture.HomeTeam) // Bring in the HomeTeam
.Include(fixture => fixture.AwayTeam); // Bring in the AwayTeam
Upvotes: 3