如何在实体框架中实现这个sql?

时间:2014-03-02 10:48:20

标签: 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.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

1 个答案:

答案 0 :(得分:0)

这篇文章展示了如何进行应该让代码运行的子查询

how to do subquery in LINQ