首页 > 解决方案 > ASP.NET Core MVC 中的导航集合返回空

问题描述

我正在构建一个显示游戏及其高分的应用程序,并同时添加游戏和高分。下面的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);
}

Razor(部分)视图 _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>

调用 _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" />

游戏类:

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()
    {
    }
}

我得到这个例外:

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

System.Linq.ThrowHelper.ThrowNoElementsException()

堆栈查询 Cookie 标头路由

InvalidOperationException:序列不包含任何元素

System.Linq.ThrowHelper.ThrowNoElementsException()
System.Linq.Enumerable.First(IEnumerable source)
AspNetCore.Views_Shared__TopByGame.ExecuteAsync() in _TopByGame.cshtml

@item.Highscores.First().Player

Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(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(TextW riter writer,对象模型,IView 视图)
Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.ProcessAsync(TagHelperContext 上下文,TagHelperOutput 输出)
Microsoft.AspNetCore.Razor。 Runtime.TagHelpers.TagHelperRunner.g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
AspNetCore.Views_Home_Index.ExecuteAsync() in Index.cshtml

ViewData["Title"] = "首页";

我无法弄清楚是什么导致了这个错误。我怀疑它与 Entity Framework Core 有关,某些转换或强制转换失败。当我查看 allGames 变量时,它似乎包含所有游戏及其高分以降序排列。我发现很难弄清楚 EF Core SQL 查询是如何工作的,以及它们需要哪些数据类型并返回。

标签: entity-framework-coreasp.net-core-mvc

解决方案


推荐阅读