在实体框架核心6中简化.Include和.TheInclude调用



我在项目中使用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

然而,它看起来很难看,而且占用了很多线条。有没有办法简化这段代码?

附言:我不想在整个上下文中使用LazyLoading,所以它不是一个选项。

您可以简化非集合导航属性的包含:

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();

最新更新