[英]Simplify .Include and .ThenInclude calls in Entity Framework Core 6
I use Entity Framework Core 6.0 in my project I have the following code structure:我在我的项目中使用 Entity Framework Core 6.0 我有以下代码结构:
public class Game
{
public Team Team1 { get; set; }
public Team Team2 { get; set; }
}
public class Team
{
public Player Player1 { get; set; }
public Race Race1 { get; set; }
public Player Player2 { get; set; }
public Race Race2 { get; set; }
}
(other fields omitted for simplicity) (为简单起见省略了其他字段)
I want to load all the data about all the games, so in my service class I do:我想加载所有游戏的所有数据,所以在我的服务 class 中我这样做:
var games = await _context.Games
.Include(g => g.Team1)
.ThenInclude(t => t.Player1)
.Include(g => g.Team1)
.ThenInclude(t => t.Race1)
.Include(g => g.Team1)
.ThenInclude(t => t.Player2)
.Include(g => g.Team1)
.ThenInclude(t => t.Race2)
.Include(g => g.Team2)
.ThenInclude(t => t.Player1)
.Include(g => g.Team2)
.ThenInclude(t => t.Race1)
.Include(g => g.Team2)
.ThenInclude(t => t.Player2)
.Include(g => g.Team2)
.ThenInclude(t => t.Race2)
.ToArrayAsync();
//Collect the statistics
However, it looks ugly and takes up a lot of lines.但是,它看起来很难看,并且占用了很多行。 Is there a way to simplify this code?
有没有办法简化这段代码?
PS I don't want to use Lazy Loading for the whole context, so it is not an option here. PS 我不想在整个上下文中使用延迟加载,所以这里不是一个选项。
You can simplify including of non-collection navigation properties:您可以简化包括非集合导航属性:
var games = await _context.Games
.Include(g => g.Team1.Player1)
.Include(g => g.Team1.Race1)
.Include(g => g.Team1.Player2)
.Include(g => g.Team1.Race2)
.Include(g => g.Team2.Player1)
.Include(g => g.Team2.Race1)
.Include(g => g.Team2.Player2)
.Include(g => g.Team2.Race2)
.ToArrayAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.