我创建了一个团队 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)。这是一张图片:
我尝试过同步和异步执行此操作,但得到了相同的结果。你知道为什么我在 json 中只得到一个结果,但在断点处它有所有结果吗?
最佳答案
将此添加到 public void ConfigureServices(IServiceCollection services)
方法内的 Startup.cs
中:
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
已讨论该问题 https://github.com/aspnet/Mvc/issues/4160和 https://github.com/aspnet/EntityFramework/issues/4646另见 circular reference
关于c# - ASP.NET Core API 仅返回列表的第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39024354/