gpt4 book ai didi

c# - 如何使用 Entity Framework Core 加载相关实体

转载 作者:行者123 更新时间:2023-11-30 12:22:54 25 4
gpt4 key购买 nike

我正在探索 Entity Framework Core,并在阅读本指南时使用代码优先方法开始 https://docs.efproject.net/en/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 的 Controller ,当我向该 Controller 发出 GET 请求时,我想获得一个 Teams 列表,其中填充了相关游戏的 Games 属性。

这是我尝试过的:

[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 属性为空。

我希望它能返回数据库中的所有球队以及每支球队的所有比赛。我怎样才能让它工作?

最佳答案

延迟加载目前未在 Entity Framework 核心中实现为 indicated here ,我建议您查看 AutoMapper 以在 POCO 中投影您想要的结果。因为你想要的恰恰会导致n+1的问题。

关于c# - 如何使用 Entity Framework Core 加载相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39022727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com