如何为sql表达式编写lambda表达式

本文关键字:表达式 lambda sql | 更新日期: 2023-09-27 18:05:52

我有一个SQL表达式

select S.SpecialtyName, COUNT(distinct SUC.SiteUserId) as Subscribers
from   SiteUserContent SUC Inner join 
       Specialties S on SUC.SpecialtyId = S.SpecialtyId Inner join 
        SiteUser SU on SUC.SiteUserId = SU.SiteUserId
where SU.DeletedFlag = 0
group by S.SpecialtyName
Order by S.SpecialtyName

对应的LINQ表达式是什么?

如何为sql表达式编写lambda表达式

from suc in context.SiteUserContent
join s in context.Specialties on suc.SpecialtyId equals s.SpecialtyId
join su in context.SiteUser on suc.SiteUserId equals su.SiteUserId
where su.DeletedFlag == 0
select new { suc.SiteUserId, s.SpecialityName } into x
group x by x.SpecialityName into g
orderby g.Key
select new { 
    SpecialityName = g.Key, 
    Subscribers = g.Select(i => i.SiteUserId).Distinct().Count()
}

生成的SQL不会相同,但我认为查询执行的结果应该是相同的

var results = contex.SiteUserContent
                    .Join(context.Specialties, suc => suc.SpecialtyId, s => s.SpecialtyId, (suc, s) => new { suc, s })
                    .Join(context.SiteUser, i = i.suc.SiteUserId, su => su.SiteUserId, (i, su) => new { suc = i.suc, s = i.s, su = su })
                    .Where(i => i.su.DeletedFlag == 0)
                    .GroupBy(i => i.s.SpecialtyName)
                    .Select(g => new {
                                     SpecialityName = g.Key,
                                     Subscribers = g.Select(i => i.suc.SiteUserId)
                                                    .Distinct()
                                                    .Count()
                                 })
                     .OrderBy(i => i.SpecialityName);