EntityFramework Core中的LINQ聚合结果

时间:2018-11-29 21:58:56

标签: linq linq-to-sql entity-framework-core

我正在尝试将此SQL重新创建为linq。

select a.Name Agency, 
      COUNT(CASE when p.AssignedAgencyId = a.Id then 1 end) Submissions,
      COUNT(CASE when p.AssignedAgencyId = a.Id AND p.SubmissionStatusId= 2 then 1 end) Rejected,
      COUNT(CASE when p.AssignedAgencyId = a.Id AND p.SubmissionStatusId= 3 then 1 end) Denied
FROM Agencies a
join projects p on p.AssignedAgencyId = a.Id
Group By  a.Name

这是我想出的,但是我不明白如何以这种方式从子查询中获取值

var agencyResults = (
                    from a in _context.Agencies
                    join p in _context.Projects on a.Id equals p.AssignedAgencyId
                    where (data.AgencyId == null || a.Id == data.AgencyId)
                    group p by p.AssignedAgencyId into g
                    select new 
                    {
                        AgencyName = (from aa in _context.Agencies
                                     where (aa.Id == data.AgencyId)
                                     select aa),
                        TotalCount = g.Count(),
                        RejectedCount = g.Count(e => e.SubmissionStatusId == 2),
                        DeniedCount = g.Count(e => e.SubmissionStatusId == 3)
                    });

enter image description here

这是我正在寻找的结果集。

2 个答案:

答案 0 :(得分:1)

我不确定您在寻找什么。但是1.阅读SQL语句,2.假设您在C#端具有完整模型并且Entities具有适当的导航属性,则可以在此LINQ中简化SQL:

var agencyResults = (
    from a in _context.Agencies
    where (data.AgencyId == null || a.Id == data.AgencyId)
    select new {
        Name = a.Name,
        Submissions = a.Projects.Count(),
        Rejected = a.Projects.Count(e => e.SubmissionStatusId == 2),
        DeniedCount = a.Count(e => e.SubmissionStatusId == 3)
    }).ToList();

P.S。不知道data是什么,它是干什么的。我只是把它放在有关问题代码段的地方(在SQL代码段中,我找不到它)。

答案 1 :(得分:0)

这是解决方案。为https://stackoverflow.com/a/9173783/823520进行我需要的推动。

     var agencyResults = (
            from p in _context.Projects
            where (data.AgencyId == null || p.AssignedAgencyId == data.AgencyId)
            group p by p.AssignedAgencyId into g
            join a in _context.Agencies on g.FirstOrDefault().AssignedAgencyId equals a.Id
            select new
            {
                AgencyName = a.Name,
                TotalCount = g.Count(),
                RejectedCount = g.Count(e => e.SubmissionStatusId == 2),
                DeniedCount = g.Count(e => e.SubmissionStatusId == 3)
            });