【发布时间】:2016-08-18 17:37:52
【问题描述】:
我创建了一个团队 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; }
}
当我这样做时:
[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 结果没有反映。这是一张图片:
我尝试过同步和异步执行此操作,但得到了相同的结果。你知道为什么我在 json 中只得到一个结果,但在断点处它有所有结果吗?
【问题讨论】:
-
我尝试了您的代码,但使用了我可用的 Users 表,它适用于两种情况...
var teams = await _context.Users.Include(u => u.Roles).ToListAsync();它只是序列化了 JSON 中的所有项目...:(跨度> -
@GerardoGrignoli 真的吗?您使用的是 Entity Framework Core 还是 Entity Framework 6?
-
我正在使用 EF Core。
-
你试过
services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });吗? -
您可以尝试将循环标记为 [JsonIgnore] 吗? [JsonIgnore] public Team Team { get;放; }
标签: c# json entity-framework asp.net-web-api asp.net-core