我正在使用Entity Framework Core进行探索,并且在阅读本指南https://docs.efproject.net/zh/latest/platforms/aspnetcore/new-db.html时,首先使用代码优先方法,但不同的模型除外。
在EF6中,它的加载是延迟的,我真的很容易拉出相关实体,但是在EF Core中无法正常工作。我想知道如何使它工作,或者是否有工作使它工作。
这是我的两个模型的示例:
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; }
}
我想为团队获得所有比赛,但截至目前为空。
我决定创建一个Web Api项目,所以我有一个名为TeamsController的控制器,当我向该控制器发出GET请求时,我想获得一个包含游戏相关属性的Games属性的Teams列表。
这是我尝试过的:
[HttpGet]
public async Task<List<Team>> Get()
{
return await _context.Teams.Include(t => t.Games).ToListAsync();
}
这是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"
}
]
}
]
当我这样做时:
[HttpGet]
public async Task<List<Team>> Get()
{
return await _context.Teams.ToListAsync();
}
我得到了所有团队,但是Games属性为null。
我希望它将返回数据库中的所有团队以及每个团队的所有游戏。我该如何工作?
延迟加载,目前没有实体框架的核心实现为在此间表示,我建议你看看AutoMapper项目在POCO您想要的结果。因为您想要的将恰好导致n + 1问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句