asp.net-mvc - 外键未显示在 View 中

标签 asp.net-mvc model-view-controller

我对 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/

相关文章:

asp.net-mvc - 为带有额外信息的图像设置虚拟路径

ios - Apple 是否违反了 iOS 8 上 MailboxContentViewCell.h 中的 MVC 规则?

javascript - 获取在 Controller 中动态添加的未排序列表列表项

ios - 如何将所有文本字段的值从 View Controller 传递到 Model 类以将模型逻辑与其分离?

asp.net-mvc - ASP.Net MVC 样式 bundle 不包含大多数文件

asp.net - 带有自定义 slugs 的 .NET MVC-4 路由

css - table.data 指的是什么?

java - Spring MVC 自定义 View

javascript - 在 MVC ASP.NET 中重新加载页面时如何在特定位置滚动页面

asp.net - Foreach 循环在模态中不起作用