带有连接和多个计数的C#LINQ查询

时间:2018-06-01 11:36:47

标签: c# sql asp.net entity-framework linq

我需要将此SQL查询转换为Linq-Entity查询

SELECT Company.name, COUNT(DISTINCT User.id), COUNT(DISTINCT Office.id)
FROM Company
INNER JOIN Office ON Company.id = Office.companyId
INNER JOIN Employee ON Office.id = Employee.officeId
GROUP BY Company.name

所以我想要一个结果,它给我一个公司的名字,独特的员工数量和一排办公室的数量。

我有这些实体

public class Company
{
    public int id { get; set; }
    public string name { get; set; }
    public List<Office> offices { get; set; }
}

public class Office
{
    public int id { get; set; }
    public string name { get; set; }
    public int companyId { get; set; }
    public List<Employee> employees { get; set; }
}

public class Employee
{
    public int id { get; set; }
    public string name { get; set; }
    public int officeId { get; set; }
}

和ViewModel:

public class MyViewModel
{
    public Company company { get; set; }
    public int employeeCount { get; set; }
    public int officeCount { get; set; }
}

我在控制器中尝试的内容:

var viewModel =
    from c in _context.Companies
    join o in _context.Offices on c.id equals o.companyId
    join e in _context.Employees on o.id equals e.officeId
    select new MyViewModel { company = c, employeeCount = ??, officeCount = 
    ??}

return View(viewModel);

所以我不知道count()和group by是如何工作的。

1 个答案:

答案 0 :(得分:2)

首先,LINQ没有直接等效的SQL COUNT(DISTINCT expr)构造。

第二个也是更重要的,在LINQ to Entities中,您不需要遵循SQL规则。我们不使用连接,而是使用导航属性,并且基本上编写查询,就像我们使用对象一样,并让EF将其转换为SQL。

有问题的LINQ to Entities查询是自然而简单的:

var query = _context.Companies
    .Select(c => new MyViewModel
    {
        company = c,
        officeCount = c.offices.Count(),
        employeeCount = c.offices.Sum(o => o.employees.Count()),
    });