我正在学习实体框架核心,并开始使用代码优先的方法,同时阅读本指南:https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html,但我的模型与此不同。
在EF6中,它具有惰性加载功能,我能轻松地获取相关的实体,但在EF Core中不能工作。我想知道如何使其工作,或者是否有解决方法可使其正常工作。
以下是我的两个模型的示例:
当我执行以下操作时:
在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请求时,我希望得到一个包含相关游戏的团队列表。
这是我尝试过的:
[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属性为空。
我希望它可以返回数据库中所有团队以及每个团队的所有比赛。如何使其正常工作?
1+n = <调用数据库>
,其中n
是数据库中团队的数量。 - Michael