如何将此SQL查询转换为DotNet Core 2.1 Linq
以下是T-SQL:如何将此SQL查询转换为DotNet Core 2.1 Linq,linq,tsql,.net-core,Linq,Tsql,.net Core,以下是T-SQL: SELECT 'Total Tournaments' AS Name, COUNT(a.location) AS Value FROM (SELECT location FROM [dbo].[TournamentBatchItem] GROUP BY TournamentName, location) a UNION SELECT 'Outdoor Tournaments' AS Name, COUNT(a.locatio
SELECT
'Total Tournaments' AS Name, COUNT(a.location) AS Value
FROM
(SELECT location
FROM [dbo].[TournamentBatchItem]
GROUP BY TournamentName, location) a
UNION
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'
输出如下所示:
Name | Value
--------------------+-------
Indoor Tournaments | 0
Outdoor Tournaments | 1
TotalTournaments | 1
var totalTournaments = (from tbi from _db.TournamentBatchItems select tbi.location).Count();
var whatever = (from tbi from _db.TournamentBatchItems where something==something select tbi.location).Count();
基本原理如下:
Name | Value
--------------------+-------
Indoor Tournaments | 0
Outdoor Tournaments | 1
TotalTournaments | 1
var totalTournaments = (from tbi from _db.TournamentBatchItems select tbi.location).Count();
var whatever = (from tbi from _db.TournamentBatchItems where something==something select tbi.location).Count();
然后使用文本字符串“Total Tournaments”手动构建列表。(或使用union命令),但我的建议是只询问count,而不询问查询中的其他内容。基本要求如下:
Name | Value
--------------------+-------
Indoor Tournaments | 0
Outdoor Tournaments | 1
TotalTournaments | 1
var totalTournaments = (from tbi from _db.TournamentBatchItems select tbi.location).Count();
var whatever = (from tbi from _db.TournamentBatchItems where something==something select tbi.location).Count();
然后使用文本字符串“Total Tournaments”手动构建列表。(或使用union命令),但我的建议是只在查询中询问count而不询问其他内容。您只需访问数据库一次即可完成此操作:
var tournaments = _db.TournamentBatchItems
// Where clause is optional, needed only if you have others locations than indoor and outdoor
.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
.GroupBy(t => t.Location)
.Select(t => new { Name = $"{ t.Key } Tournaments", Value = t.Count()})
.ToList();
tournaments.Add(new { Name = "Total Tournaments", Value = tournaments.Sum(t => t.Value)});
您只需访问数据库一次即可完成此操作:
var tournaments = _db.TournamentBatchItems
// Where clause is optional, needed only if you have others locations than indoor and outdoor
.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
.GroupBy(t => t.Location)
.Select(t => new { Name = $"{ t.Key } Tournaments", Value = t.Count()})
.ToList();
tournaments.Add(new { Name = "Total Tournaments", Value = tournaments.Sum(t => t.Value)});