如何在实体框架中实现此sql?

如何在实体框架中实现此sql?,sql,linq,entity-framework,linq-to-entities,Sql,Linq,Entity Framework,Linq To Entities,SQL是: select a.Id, a.Name,a. ParentId, sum(a.departmentCount), sum(a.userCount) from (select d.*, 0 as departmentCount, count(u.Id) as userCount from dbo.DepartmentSet d left join dbo.UserSe

SQL是:

select 
   a.Id, a.Name,a. ParentId,
   sum(a.departmentCount),
   sum(a.userCount) 
from
   (select 
       d.*,
       0 as departmentCount,
       count(u.Id) as userCount
    from 
       dbo.DepartmentSet d
    left join 
       dbo.UserSet u on d.Id = u.DepartmentId
    where 
       d.ParentId is null
    group by 
       d.Id, d.Name, d.ParentId 

    union all

    select 
       d.*,
       count(d2.Id) as departmentCount,
       0 as userCount
    from 
       dbo.DepartmentSet d
    left join 
       dbo.DepartmentSet d2 on d.Id = d2.ParentId
    where 
       d.ParentId is null
    group by 
       d.Id, d.Name, d.ParentId) a
group by 
    a.Id, a.Name, a.ParentId

下面是一篇文章,它展示了如何进行子查询,这些子查询将使您的代码正常运行