模型

时间:2016-01-19 02:02:18

标签: asp.net-mvc entity-framework

我想制作一个这样的模型:

public class Competition
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public string Description { get; set; }
    public ICollection<GameResult> PlayedGames { get; set; }
}

其中GameResult是一个包含简单字段的类。 我加一个:

context.Competitions.Add(new Competition()
            {
                Name = "Default competition",
                Description = "This is a sample of a competition rules. Hope its seems good :3",
                PlayedGames = new List<GameResult> {new GameResult {Id = 1, LeftPlayer = "left", RightPlayer = "right", LeftScore = 10, RightScore = 20} },
                IsActive = true
            });
            context.SaveChanges();

当我尝试从context.Competitions获取值时,其他字段有值,但“PlayedGames”为空。

我想这是因为它是一个引用类型的类。 我需要用外键创建另一个表? 我怎么能在“Code First”中做到这一点?

1 个答案:

答案 0 :(得分:2)

您需要将导航属性定义为virtual

public class Competition
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public string Description { get; set; }
    public virtual ICollection<GameResult> PlayedGames { get; set; }
}

检查here您的实体必须遵守的要求。这样,EF将创建一个从您的类派生的代理类,并使用它来代替处理lazy loading并跟踪更改的原始类。

加载相关属性的另一种方法是使用eager loading

var query= context.Competitions
                  .Include(c=>c.PlayedGames) //using this method you are going to load the related entity as part of your query
                  .FirstOrDefault();