如何在C#中将此T-SQL查询转换为lambda或查询语法

时间:2019-04-27 19:55:27

标签: c# sql-server lambda syntax

我是C#中的Entity Framework的新手。我正在尝试将此SQL语句转换为lambda表达式或查询语法,但似乎无法弄清楚该怎么做。

这是SQL查询:

SELECT
    a.Id, a.IndustryName, 
    COUNT(b.ProcessJobPostNumId) AS IndustryCount 
FROM
    ERECRUITDEV.dbo.Industries a
LEFT JOIN
    (SELECT 
         b.IndustryID, b.Id AS JobPostId, d.MdaId, c.ParishID, 
         c.EmploymentType, c.Id AS JobPostNumId, 
         d.Id AS ProcessJobPostNumId, e.AvailableInternal  
     FROM 
         ERECRUITDEV.dbo.JobPost b
     LEFT JOIN
         ERECRUITDEV.dbo.JobPostNumber c ON c.JobPostId = b.id
     LEFT JOIN
         ERECRUITDEV.dbo.ProcessJobPostNum d ON d.JobPostNumId = c.Id
     LEFT JOIN
         ERECRUITDEV.dbo.RecruitmentProcess e ON e.id = d.RecruitProcessId 
     WHERE
         AvailableInternal = 1) b ON b.IndustryID = a.Id
GROUP BY 
    a.Id, a.IndustryName

1 个答案:

答案 0 :(得分:0)

正如您所告知的那样,对于您在提供的查询中进行的每个联接,所有实体对象都包含导航属性,那么下面的lambda表达式应该像一个超级按钮一样工作;

var result = context.Industries.Select(i => new {
    i.Id,
    i.IndustryName,
    IndustryCount = i.JobPosts
        .Where(jp => jp.JobPostNumbers
            .Any(jpn => jpn.ProcessJobPostNums
                .Any(pjpn => pjpn.RecruitmentProcess
                    .Any(rp => rp.AvailableInternal == 1))))
        .SelectMany(jp => jp.ProcessJobPostNums
            .SelectMany(jpn => jpn.ProcessJobPostNums
                .Select(pjpn => pjpn.Id)))
        .Count()
}).ToList();