简体   繁体   中英

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:

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:

        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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM