Entity framework core ASP.NET核心MVC中的导航集合返回为空

Entity framework core ASP.NET核心MVC中的导航集合返回为空,entity-framework-core,asp.net-core-mvc,Entity Framework Core,Asp.net Core Mvc,我正在构建一个显示游戏及其高分的应用程序,同时添加游戏和高分。下面的IActionResult方法总是给我一个错误,表明我无法为游戏添加高分。我想在Razor视图中显示所有游戏的最高分数 public IActionResult Index() { IEnumerable<Game> allGames = _db.Games; foreach (var game in allGames) { IEnumerable<Highscore&

我正在构建一个显示游戏及其高分的应用程序,同时添加游戏和高分。下面的
IActionResult
方法总是给我一个错误,表明我无法为游戏添加高分。我想在Razor视图中显示所有游戏的最高分数

public IActionResult Index()
{
    IEnumerable<Game> allGames = _db.Games;

    foreach (var game in allGames)
    {
        IEnumerable<Highscore> hiScoresForGame = _db.Highscores.Where(h => h.GameId == game.Id);
        game.Highscores = hiScoresForGame.OrderByDescending(hs => hs.Score).ToList();
    }
    return View(allGames);
}
public IActionResult Index()
{
IEnumerable allGames=\u db.Games;
foreach(所有游戏中的var游戏)
{
IEnumerable hiscoresforganame=\u db.Highscores.Where(h=>h.GameId==game.Id);
game.Highscores=hiscoresforme.OrderByDescending(hs=>hs.scores.ToList();
}
返回视图(所有游戏);
}
Razor(部分)视图\u TopByGame.cshtml:

@model IEnumerable<HighScoresV1.Models.Game>

<table class="table">
    <thead>
        <tr>
            <th>
                Game
            </th>
            <th>
                Player
            </th>
            <th>
                Day achieved
            </th>
            <th>
                Score
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <a asp-controller="Game" asp-action="Details" asp-route-urlSlug="@item.UrlSlug">@item.Title</a>
                </td>
                <td>
                    @item.Highscores.First().Player
                </td>
                <td>
                    @item.Highscores.First().DayAchieved
                </td>
                <td>
                    @item.Highscores.First().Score
                </td>
            </tr>
        }
    </tbody>
</table>
@model IEnumerable
游戏
玩家
完成的一天
分数
@foreach(模型中的var项目)
{
@项目.标题
@item.Highscores.First().Player
@item.Highscores.First().DayAcquired
@item.Highscores.First().scores
}
视图调用TopByGame

@model IEnumerable<HighScoresV1.Models.Game>

@{
    ViewData["Title"] = "Home";
}
<div class="row ml-auto mr-auto">
    <span class="h1 text-danger mt-5 mb-5 font-weight-bolder col-9">Top highscore for each game</span>
    <a asp-controller = "Highscore" asp-action="Create" class="btn btn-primary w-50 ml-auto mt-auto mb-auto col-3">Register New Highscore</a>
</div>
<partial name="_TopByGame" />

@model IEnumerable
@{
ViewData[“标题”]=“主页”;
}
每场比赛的最高得分
再创新高
游戏类:

public class Game
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    public string Description { get; set; }

    [Range(1900, int.MaxValue, ErrorMessage = "Release year must be in the 20th century or later")]
    [DisplayName("Release Year")]
    public int ReleaseYear { get; set; }

    [Required]
    public string ImageUrl { get; set; }

    // Relationship (Game - Genre) = One-to-many.
    // A Game is in one Genre. A Genre can have many games

    [DisplayName("Genre of game")]
    public int GenreId { get; set; }
    [ForeignKey("GenreId")]
    public virtual Genre Genre { get; set; }

    [Required]
    [MaxLength(50)]
    public string UrlSlug { get; set; }
    [Required]
    public IEnumerable<Highscore> Highscores { get; set; }

    public Game(string title, string description, int releaseYear, string imageUrl)
    {
        Title = title;
        Description = description;
        ReleaseYear = releaseYear;
        ImageUrl = imageUrl;
        UrlSlug = title.Slugify();
        Highscores = new List<Highscore>();
    }

    public Game(string title, string description, int releaseYear, string imageUrl, string urlSlug)
        :this(title, description, releaseYear, imageUrl)
    {
        UrlSlug = urlSlug;
    }

    public Game(int id, string title, string description, int releaseYear, string imageUrl, string urlSlug)
        : this(title, description, releaseYear, imageUrl)
    {
        Id = id;
        UrlSlug = urlSlug;
    }

    public Game()
    {
    }
}
公共类游戏
{
[关键]
公共int Id{get;set;}
[必需]
公共字符串标题{get;set;}
公共字符串说明{get;set;}
[范围(1900,int.MaxValue,ErrorMessage=“发布年份必须在20世纪或更高版本”)]
[显示名称(“发布年份”)]
public int ReleaseYear{get;set;}
[必需]
公共字符串ImageUrl{get;set;}
//关系(游戏类型)=一对多。
//一个游戏有一种类型。一种类型可以有很多游戏
[DisplayName(“游戏类型”)]
public int GenreId{get;set;}
[ForeignKey(“GenreId”)]
公共虚拟类型{get;set;}
[必需]
[MaxLength(50)]
公共字符串UrlSlug{get;set;}
[必需]
公共IEnumerable高分{get;set;}
公共游戏(字符串标题、字符串描述、int releaseYear、字符串图像URL)
{
头衔=头衔;
描述=描述;
ReleaseYear=ReleaseYear;
ImageUrl=ImageUrl;
UrlSlug=title.Slugify();
高分=新列表();
}
公共游戏(字符串标题、字符串描述、int releaseYear、字符串imageUrl、字符串urlSlug)
:此(标题、说明、发布年份、图像URL)
{
UrlSlug=UrlSlug;
}
公共游戏(int-id、字符串标题、字符串描述、int-releaseYear、字符串imageUrl、字符串urlSlug)
:此(标题、说明、发布年份、图像URL)
{
Id=Id;
UrlSlug=UrlSlug;
}
公共游戏()
{
}
}
我得到一个例外:

处理请求时发生未处理的异常。
InvalidOperationException:序列不包含元素

System.Linq.ThrowHelper.ThrowNoElementsException()

堆栈查询Cookies头路由

InvalidOperationException:序列不包含元素

System.Linq.ThrowHelper.ThrowNoElementsException()
System.Linq.Enumerable.First(IEnumerable source)
AspNetCore.Views\u Shared\u\u TopByGame.ExecuteAsync()在\u TopByGame.cshtml中

@item.Highscores.First().Player

Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAncync(IRazorPage页面,ViewContext上下文)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage页面、ViewContext上下文、bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext上下文)
Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.RenderPartialViewAsync(文本编写器、对象模型、IView视图)
Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.ProcessAsync(TagHelperContext上下文,TagHelperOutput输出)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.g_u等待| 0_0(任务任务,TagHelperExecutionContext executionContext,int i,int count)
Index.cshtml中的AspNetCore.Views\u Home\u Index.ExecuteAsync()

ViewData[“标题”]=“主页”


我不知道是什么导致了这个错误。我怀疑这与实体框架核心有关,一些转换或强制转换失败。当我查看allGames变量时,它似乎包含所有游戏以及它们的高分(按降序排列)。我发现很难弄清楚EF核心SQL查询是如何工作的,它们需要哪些数据类型并返回。

我相信我解决了这个问题,方法是将部分视图中的foreach包装到if块中,检查game.Highscore.Count()==0。有一场比赛没有得分,这可能会导致空引用错误。