在C#中,如何对实体集合属性进行排序?

时间:2019-07-06 20:22:01

标签: c# asp.net-core

我正在使用Microsoft的“ ASP.NET Core中带有Entity Framework Core的Razor Pages”教程构建网站,该教程构建了示例Contoso University Web应用程序(https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-2.2&tabs=visual-studio)。在我的Web应用程序中,我有一个类Groups,其中包含Office的集合,并且Office属性之一是OfficeName-我想对OfficeName进行排序。 在Contoso大学的示例中,这类似于单击“教师”链接并按字母顺序对课程标题进行排序。我一直在尝试使用Include和ThenInclude方法加载属性,但是无法通过“课程标题”属性执行OrderBy。

这是教师模型-

public class Instructor
{
    public int ID { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }        

    public ICollection<CourseAssignment> CourseAssignments { get; set; }
    public OfficeAssignment OfficeAssignment { get; set; }
    public ICollection<Course> Courses { get; set; }
}

这是课程模型-

public class Course
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Display(Name = "Number")]
    public int CourseID { get; set; }

    [StringLength(50, MinimumLength = 3)]
    public string Title { get; set; }  . . .

    public ICollection<Enrollment> Enrollments { get; set; }

    public ICollection<CourseAssignment> CourseAssignments { get; set; }
}

Contoso大学样本讲师的Index.cshtml.cs-

    public async Task OnGetAsync(int? id, int? courseID)
    {
        Instructor = new InstructorIndexData();
        Instructor.Instructors = await _context.Instructors
            .Include(i => i.OfficeAssignment)
            .Include(i => i.CourseAssignments)
                .ThenInclude(i => i.Course)
                    .ThenInclude(i => i.Department)
            .Include(i => i.CourseAssignments)
                .ThenInclude(i => i.Course)
                    .ThenInclude(i => i.Enrollments)
                        .ThenInclude(i => i.Student)
            .AsNoTracking()
            .OrderBy(i => i.LastName)
            .ToListAsync();

        if (id != null)
        {
            InstructorID = id.Value;
            Instructor instructor = Instructor.Instructors.Where(
                i => i.ID == id.Value).Single();
            Instructor.Courses = instructor.CourseAssignments.Select(s => s.Course);
        }

        if (courseID != null)
        {
            CourseID = courseID.Value;
            Instructor.Enrollments = Instructor.Courses.Where(
                x => x.CourseID == courseID).Single().Enrollments;
        }
    }

“教师索引”页面上的每位教师均按他们未教授的课程排序。如何排序孩子(课程标题)?

0 个答案:

没有答案