【问题标题】:EF6 Code First MVC Related Entity nullEF6 代码优先 MVC 相关实体 null
【发布时间】:2014-08-18 21:46:18
【问题描述】:

我有这两个类:

public class Players
{
    [Key]
    public int Id { get; set; }
    public string PlayerName { get; set; }

    public virtual ICollection<ResultItems> ResultItems { get; set; }
}

public class ResultItems
{
    [Key]
    public int Id { get; set; }
    public int ResultsId { get; set; }
    public Results Results { get; set; }
    public int Position { get; set; }
    public int PlayerId { get; set; }
    public Players Player { get; set; }
    public double Cash { get; set; }
    public int Points { get; set; }
}

当我们输入 ResultItems 时,您会在这里看到数据库的填充效果很好:

但是,当页面加载时,我们循环遍历模型以创建数据表,Player 实体为空:

有人可以帮我理解为什么它没有加载吗?任何帮助将不胜感激。

谢谢,

保罗。

【问题讨论】:

  • 查询时需要包含播放器。 db.ResultItems.Include("Player").ToList()
  • 谢谢。这就是诀窍。你知道为什么这个包含方法必须在 DbContext 上运行吗?在我使用 EF 的所有其他情况下,主对象只会“延迟加载”子对象。
  • virtual 添加到您的 Player 对象。

标签: asp.net-mvc entity-framework code-first


【解决方案1】:

您需要将virtual 关键字添加到您的public Players Player 或者您可以添加db.ResultItems.Include("Player").ToList()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多