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

标签 c# json entity-framework asp.net-web-api asp.net-core

我创建了一个团队 web api Controller 并尝试调用 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; }
}

当我这样做时:

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

    return teams;
}

我得到了所有 254 个团队,但 Game 属性为空,因为 EF Core 不支持延迟加载。所以我真正想做的是像这样添加 .Include() :

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

    return teams;
}

这将返回第一支球队,但没有其他任何东西。这是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"
      }
    ]
  }
]

当我在 return 语句上设置断点时,它显示有 254 支球队,每支球队都正确填充了他们的比赛......但 json 结果没有反射(reflect)。这是一张图片:

enter image description here

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

最佳答案

将此添加到 public void ConfigureServices(IServiceCollection services) 方法内的 Startup.cs 中:

services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

已讨论该问题 https://github.com/aspnet/Mvc/issues/4160https://github.com/aspnet/EntityFramework/issues/4646另见 circular reference

关于c# - ASP.NET Core API 仅返回列表的第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39024354/

相关文章:

c# - 从 EF 返回 2 列的自定义列表

c# - 在 .NET 中操作 XML 的最佳方式

javascript - 为什么返回原始 JSON 对象而不是我的部分 View ?

ruby-on-rails - 如何组合不同的 json jbuilder View ?

java - 如何检查下面的 JSON 响应是否为空数组

.net - 如何创建嵌套 :many relationships in Entity Framework?

c# - sql 'timestamp' 列真的是 'byte[]' 吗?

c# - 如何在我的 LINQ 中实现对数据库的单次调用?

c# - 平台构建器中的 DLL

c# - 如何使用 C# 删除 Windows 用户帐户