【发布时间】:2018-06-01 11:36:47
【问题描述】:
我需要将此 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 是如何工作的。
【问题讨论】:
-
能否添加查询的输入输出示例截图。
-
您没有在任何地方使用组运算符。
标签: c# sql asp.net entity-framework linq