SQL Server The LINQ expression could not be translated when trying to use .All() to List< string>

nwsw7zdq  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(119)

My linq query fails when I try to execute it on db side:

public async Task<List<MatchEntity>> GetMatchesAsync(List<string> teammatesChampionNames, List<string> enemiesChampionNames)
    {
        return await _context.Matches.Include(x => x.Teams).ThenInclude(x => x.Participants).AsSplitQuery()
            .Where(x =>
                teammatesChampionNames.All(y => x.Teams.Any(z => z.Participants.Any(i => i.ChampionName == y)))
                && enemiesChampionNames.All(y => x.Teams.Any(z => z.Participants.Any(i => i.ChampionName == y)))).ToListAsync();
    }

Do you know whether it is possible to rewrite it? I am using .EF Core 7 and SQL Server

9rygscc1

9rygscc11#

For the first condition ( teammatesChampionNames.All... ), the idea is that if all ChampionName s of all Particiants of all Teams are collected, you want the Matches where all of these names occur in teammatesChampionNames . This is true if teammatesChampionNames contains these names and when there are as many of these occurring names as there are in teammatesChampionNames .

Applying the same reasoning to the second condition, the query can be rewritten in this form that EF can translate:

return await
(
    from match in _context.Matches
    let championNames = match.Teams
        .SelectMany(x => x.Participants)
            .Select(p => p.ChampionName)
    let teammates = championNames.Where(n => teammatesChampionNames.Contains(n)).Distinct()
    let enemies = championNames.Where(n => enemiesChampionNames.Contains(n)).Distinct()
    where teammates.Count() = teammatesChampionNames.Count()
       && enemies.Count() = enemiesChampionNames.Count()
).ToListAsync((;

相关问题