【问题标题】:Simplify .Include and .ThenInclude calls in Entity Framework Core 6在 Entity Framework Core 6 中简化 .Include 和 .ThenInclude 调用
【发布时间】:2022-01-17 21:15:30
【问题描述】:

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

但是,它看起来很丑,而且占用了很多行。 有没有办法简化这段代码?

附:我不想在整个上下文中使用延迟加载,所以这里不是一个选项。

【问题讨论】:

  • 请说一下表之间的关系。(一对一或多对多或一对多)
  • 游戏有两支球队,每支球队有两名球员和两个种族。所以它是一对多

标签: c# entity-framework-core


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2022-01-25
    • 2017-08-05
    • 2013-12-28
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多