我对 MVC 方法有点陌生。我首先从数据库模型开始。我目前有两个表:
- 赛程
- 团队
赛程(以及其他字段)有一个指向主队和客队球队表的 FK 链接。
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; }
}
我注意到,当这到达 FixtureController 时,HomeTeam 和 AwayTeam 对象都为 null。我是否必须以某种方式在 Controller 内部连接它还是应该自动建立连接?
所以理想情况下,我可以拥有:
<td>
@Html.DisplayFor(modelItem => item.HomeTeam.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.AwayTeam.Name)
</td>
所以我想我的问题是如何让我的 Controller 从 Fixtures->Team 建立链接?
谢谢
最佳答案
在 Controller 中,使用 .Ininclude
获取数据。另请参阅: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
关于asp.net-mvc - 外键未显示在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249377/