EF6 Code First MVC相关实体null

时间:2014-08-18 21:46:19

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

我有这两个类:

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时数据库填充得很好:

screenshot

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

screenshot

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

谢谢,

保罗。

1 个答案:

答案 0 :(得分:2)

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