首页 > 解决方案 > LINQ 方法查询中的多选问题

问题描述

我们有这个 TSQL:

SELECT 'Outdoor Tournaments' AS Name, COUNT(a.location) AS Value
FROM
(select location
from [dbo].[TournamentBatchItem]
GROUP BY TournamentName, location) a
WHERE a.location = 'Outdoor'

UNION

SELECT 'Indoor Tournaments' AS Name, COUNT(a.location) AS Value
FROM
(select location
from [dbo].[TournamentBatchItem]
GROUP BY TournamentName, location) a
WHERE a.location = 'Indoor'

LINQ 方法的初始解决方案:

var tournamentStats1 = await _context.TournamentBatchItem.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
                          .GroupBy(t => t.Location)                                        
                          .Select(t => new { Name = t.Key, Value = t.Location})
                          .ToListAsync();

然后我们意识到这不是正确的,我们对此进行了修改并测试了 LinqPAD应用程序并运行正常:

var tournamentStats1 = await _context.TournamentBatchItem.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
                          .GroupBy(t => new { t.TournamentName, t.Location })
                          .Select(t => new { Name = t.Key.TournamentName, Value = t.Key.Location })
                          .GroupBy(a => a.Value)
                          .Select(a => new Stat { Name = a.Key, Value=a.Count() })
                          .ToList();

但是,当我们放入 .Net Core 2.1 Web 应用程序时,我们有这个“System.ArgumentException: must be reducible node”,它看起来与嵌套选择有关,所以我们通过拆分查询将其修改为下面。这个工作正常。

var tournamentStats1 = await _context.TournamentBatchItem.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
                                    .GroupBy(t => new { t.TournamentName, t.Location })
                                    .Select(t => new { Name = t.Key.TournamentName, Value = t.Key.Location })
                                    .ToListAsync();


            var tournamentStats = tournamentStats1.GroupBy(a => a.Value)
                                    .Select(a => new Stat { Name = a.Key, Value=a.Count() })
                                    .ToList();

这是一个错误吗?有人有这个 2.1 版本的经验吗?

谢谢

标签: linq.net-coreentity-framework-core

解决方案


推荐阅读