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

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

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

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

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:

  1. return await
  2. (
  3. from match in _context.Matches
  4. let championNames = match.Teams
  5. .SelectMany(x => x.Participants)
  6. .Select(p => p.ChampionName)
  7. let teammates = championNames.Where(n => teammatesChampionNames.Contains(n)).Distinct()
  8. let enemies = championNames.Where(n => enemiesChampionNames.Contains(n)).Distinct()
  9. where teammates.Count() = teammatesChampionNames.Count()
  10. && enemies.Count() = enemiesChampionNames.Count()
  11. ).ToListAsync((;
展开查看全部

相关问题