我在项目中使用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; }
}
(为简单起见,省略了其他字段)
我想加载所有游戏的所有数据,因此在我的服务类中,我会:
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
然而,它看起来很难看,占用了很多线。有没有办法简化这段代码?
另外,我不想在整个上下文中使用延迟加载,所以在这里它不是一个选项。
您可以简化包括非集合导航属性:
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();