在Entity Framework中的每个父属性中获取最佳结果

时间:2016-12-25 20:22:40

标签: c# entity-framework linq

我正在尝试选择每个部门中报告最多的员工。虽然在实体框架中使用LINQ,但我无法弄清楚如何做到这一点。我正在使用EF Core,但答案应与EF 6相同,因此任何一个的答案都可行。我知道我需要使用.Distinct(),但我不确定如何正确使用它。

如何让每个部门的员工获得最多报告?查询应该返回一个列表(或可查询的)员工。

public class Employee
{
    public long Id { get; set; }
    public string Name { get; set; }

    public long DepartmentId { get; set; }
    public Department Department { get; set; }

    public ICollection<Report> Reports { get; set; }
}

public class Department
{
    public long Id { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

这就是我的开始,但我不确定它是否是正确的开始方式。

var employees = _context.Employees
    .OrderByDescending(e => e.Reports.Count)
    // ?

3 个答案:

答案 0 :(得分:1)

从每个部门获取报告最多的员工:

var employees = _context.Departments.Select(department => 
                  department.Employees.OrderByDescending(employee => employee.Reports.Count).FirstOrDefault()).ToList();

答案 1 :(得分:1)

您应该在部门级别开始查询。在每个部门内,让其员工获得最高的报告数:

var topEmpPerDep = _context.Departments
    .Select(dep => new
    {
        Department = dep.Name,
        Employee = dep.Employees.OrderByDescending(e => e.Reports.Count)
           .FirstOrDefault().Name
    });

答案 2 :(得分:0)

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var results = Department.departments.Select(x => new {
                deptmentName = x.Name,
                maxEmployeeReports = x.Employees.Select(y => new { name = y.Name, count = y.Reports.Count, employee = y }).OrderByDescending(z => z.count).FirstOrDefault()
            }).ToList();
        }
    }
    public class Employee
    {
        public long Id { get; set; }
        public string Name { get; set; }

        public long DepartmentId { get; set; }
        public Department Department { get; set; }

        public ICollection<Report> Reports { get; set; }
    }

    public class Department
    {
        public long Id { get; set; }
        public string Name { get; set; }

        public ICollection<Employee> Employees { get; set; }
        public static List<Department> departments = new List<Department>();
    }
    public class Report
    {
    }
}