Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 模型中的引用类型类字段_Asp.net Mvc_Entity Framework - Fatal编程技术网

Asp.net mvc 模型中的引用类型类字段

Asp.net mvc 模型中的引用类型类字段,asp.net-mvc,entity-framework,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> Pla

我想做一个这样的模型:

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; }
}
公开课竞赛
{
公共int Id{get;set;}
[必需]
公共字符串名称{get;set;}
公共bool IsActive{get;set;}
公共字符串说明{get;set;}
公共ICollection 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.Add(新竞争()
{
Name=“默认竞争”,
Description=“这是一个竞赛规则的示例。希望它看起来不错:3”,
PlayedGames=新列表{新游戏结果{Id=1,LeftPlayer=“left”,RightPlayer=“right”,LeftScore=10,RightScore=20},
IsActive=true
});
SaveChanges();
当我试图从context.Competitions中获取值时,其他字段都有值,但“PlayedGames”为空

我猜这是因为它是一个引用类型的类。 我需要用外键再做一张桌子?
如何在“代码优先”中执行此操作?

您需要将导航属性定义为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; }
}
我只是用了“包括”和它的作品。泰。这意味着GameResult被添加到DB中,但要获得它,我们需要“请求”包含它?好的,很好:)
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();