ASP.NET Core API仅返回列表的第一个结果

Aar*_*ron 33 c# json entity-framework asp.net-web-api asp.net-core

我创建了一个团队web api控制器,并尝试调用GET方法来获取数据库中所有团队的json结果.但是当我打电话时,我只让第一支队伍回到了json,但是当我在return语句上设置一个断点时,它拥有所有254支球队以及所有比赛.

这些是我正在处理的两个模型:

public class Team
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Icon { get; set; }
    public string Mascot { get; set; }
    public string Conference { get; set; }
    public int NationalRank { get; set; }

    public List<Game> Games { get; set; }
}

public class Game
{
    public string Id { get; set; }
    public string Opponent { get; set; }
    public string OpponentLogo { get; set; }
    public string GameDate { get; set; }
    public string GameTime { get; set; }
    public string TvNetwork { get; set; }
    public string TeamId { get; set; }

    public Team Team { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我这样做:

[HttpGet]
public async Task<List<Team>> Get()
{
    var teams = await _context.Teams.ToListAsync();

    return teams;
}
Run Code Online (Sandbox Code Playgroud)

我获得了所有254个团队,但Game属性为null,因为EF Core不支持延迟加载.所以我真正想做的是添加.Include(),如下所示:

[HttpGet]
public async Task<List<Team>> Get()
{
    var teams = await _context.Teams.Include(t => t.Games).ToListAsync();

    return teams;
}
Run Code Online (Sandbox Code Playgroud)

这将使第一个团队返回第一个游戏,但没有别的.这是json:

[
  {
    "id": "007b4f09-d4da-4040-be3a-8e45fc0a572b",
    "name": "New Mexico",
    "icon": "lobos.jpg",
    "mascot": "New Mexico Lobos",
    "conference": "MW - Mountain",
    "nationalRank": null,
    "games": [
      {
        "id": "1198e6b1-e8ab-48ab-a63f-e86421126361",
        "opponent": "vs Air Force*",
        "opponentLogo": "falcons.jpg",
        "gameDate": "Sat, Oct 15",
        "gameTime": "TBD ",
        "tvNetwork": null,
        "teamId": "007b4f09-d4da-4040-be3a-8e45fc0a572b"
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

当我在return语句上设置一个断点时,它表明有254个团队,每个团队都正确填充了他们的游戏......但是json结果没有反映出来.这是一张图片:

在此输入图像描述

我已尝试同步和异步执行此操作,但获得相同的结果.你知道为什么我只在json中得到一个结果但在断点处它有所有结果吗?

ade*_*lin 50

试试这个:

services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });
Run Code Online (Sandbox Code Playgroud)

讨论的问题https://github.com/aspnet/Mvc/issues/4160https://github.com/aspnet/EntityFramework/issues/4646也看到了循环参考

  • 最令人沮丧的错误 (6认同)
  • 就像ASP.NET Core 2.0中的魅力一样 (3认同)
  • 这应该在官方文档中提到:( (3认同)