ASP.NET MVC 3(实体框架)中的Order by Collection实体属性

本文关键字:实体 中的 Order by 属性 Collection 框架 NET MVC ASP | 更新日期: 2023-09-27 18:27:27

我有两个实体,比如:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Lastname { get; set; }
    public virtual ICollection<EmployeeEducation> EducationList { get; set; }
}

public class EmployeeEducation
{
    public int Id { get; set; }
    public int EmployeeId { get; set; }
    public int Type { get; set; }
    [ForeignKey("EmployeeId")]
    public virtual Employee Employee { get; set; }
}

我的问题是,如何获取按Type属性排序的特定员工和该员工的教育列表?

我试过:

Employee employee = _work.EmployeeRepository.GetSet()
    .SelectMany(e => e.EducationList, (e,d) => new { e, d })
        .OrderBy(x => x.d.Type)
        .Select(x => x.e)
   .FirstOrDefault(e => e.Id == id);

但它似乎没有分类。正确的方法是什么?

谢谢大家。。。

ASP.NET MVC 3(实体框架)中的Order by Collection实体属性

您执行SelectMany(),但永远不要使用生成的EducationList部分,因为您执行的是.Select(x => x.e)。但是生活难道不能更简单吗?毕竟,你只有一个员工,为什么不在有Include d之后,如果需要的话,立即对其EducationList进行排序呢:

Employee employee = _work.EmployeeRepository.GetSet().Include("EducationList")
.FirstOrDefault(e => e.Id == id);

根据您是否使用POCO,您应该使用CreateSourceQuery()或Query()在POCO的情况下,类似于:

Employee employee = _work.EmployeeRepository.GetSet()
    .SelectMany(e => e.EducationList, (e,d) => new { e, d })
        .Query()
        .OrderBy(x => x.d.Type)
        .Select(x => x.e)
   .FirstOrDefault(e => e.Id == id);