如何将 SQL 语句转换为 LINQ?

How to convert SQL statement to LINQ?

我的问题是像 SQL 查询一样,用另外 4 个不同的布尔类型列提取不同的 PartId。图 1 展示了我想要的输出。问题是,如果我们假设默认使用 dBcontext,我如何使用 LINQ 和 EF Core 解决同样的问题。更重要的是假设对象 ApprovalNumberRecord 是 DbSet 并且可以导航到 Part 和 Approval 对象。

SELECT
    B.PartId
    ,Sum(Case when B.ApprovalName = 'R-67' then 1 Else 0 End) as [R-67]
    ,Sum(Case when B.ApprovalName = 'R115' then 1  Else 0 End) as [R115]
    ,Sum(Case when B.ApprovalName = 'LPG-D' then 1  Else 0 End) as [LPG-D]
    ,Sum(Case when B.ApprovalName = 'CNG-D' then 1  Else 0 End) as [CNG-D]
FROM
    (SELECT 
         anr.PartId
         ,a.ApprovalName
         ,anr.IsVisible
         ,p.[Description]
     FROM 
         ApprovalNumberRecord AS anr
     LEFT JOIN
         Parts AS p ON anr.PartId = p.Id
     LEFT JOIN
         Approvals AS a ON anr.ApprovalId = a.Id) AS B 
GROUP BY
    B.PartId

Output of SQL statement

这是内部 SELECT 输出:

OUTPUT of inner SQL statement

数据库模型下方:

ApprovalNumberRecordclass:

... //other fields and properties

public Part Part { get; set; }
public Approval Approval { get; set; }

部分 class:

public Producer Producer{ get; set; }
public Category Category { get; set; }
public ICollection<ApprovalNumberRecord> ApprovalNumberRecords { get; set; }

批准class:

none navigation objects inside

var innerQuery =
  from anr in dbContext.ApprovalNumberRecords
  let p = anr.Part
  let a = anr.Approval
  select new { anr.PartId, a?.ApprovalName, anr.IsVisible, p?.Description };

var groupQuery =
  from B in innerQuery
  group B by B.PartId into g
  select new {
    PartId = g.Key,
    R_67 = g.Sum(x => x.ApprovalName == 'R-67' ? 1 : 0),
    R115 = g.Sum(x => x.ApprovalName == 'R111' ? 1 : 0),
    LPG_D = g.Sum(x => x.ApprovalName == 'LPG-D' ? 1 : 0),
    CNG_D = g.Sum(x => x.ApprovalName == 'CNG-D' ? 1 : 0)
  };