LINQ 包含 select 的子数组

LINQ Include a child array of select

我有以下 LINQ 查询,它运行良好:

public IList<Course> GetEmployeeCourses(int id) {
  var employeeCourses = Context.Employees
    .Where(e => e.Id == id)
    .SelectMany(e => e.employeeCourses.Select(ec => ec.Course))
    .ToList();

  return employeeCourses;
}

问题是,我现在还需要在返回课程数组时包含所选课程的子数组 (Urls)。

类似于:

public IList<Course> GetEmployeeCourses(int id) {
  var employeeCourses = Context.Employees
    .Where(e => e.Id == id)
    .SelectMany(e => e.employeeCourses.Select(ec => ec.Course))
    .Include(c => c.Urls)
    .ToList();

  return employeeCourses;
}

它像这样返回 JSON :(虽然课程模型有超过 15 个属性)

[
  {
     "Name": "Course1",
     "Type": "Maths",
     "Location": "Block C",
     "Urls": [
          {
            "Link": "https://url1forcourse1.com"
          },
          {
            "Link": "https://url2forcourse1.com"
          }
      ]
  }
  {
     "Name": "Course2"
     "Type": "Computer Science",
     "Location": "Block A",
     "Urls": [
          {
            "Link": "https://url1forcourse2.com"
          },
          {
            "Link": "https://url2forcourse2.com"
          }
      ]
  },
  {
     "Name": "Course3"
     "Type": "The Art of Dish Washing",
     "Location": "Block E",
     "Urls": [
          {
            "Link": "https://url1forcourse3.com"
          },
          {
            "Link": "https://url2forcourse3.com"
          }
      ]
  }
]

我将如何以最有效的方式实现这一目标?我现在似乎根本无法获得名为 'Urls' 的子数组,它始终为空。

另外,我使用 Fluent API 和这个 EmployeeCourse 配置:

ToTable("EmployeeCourses");

HasKey(q => new { q.CourseId, q.Employee.Id})

HasRequired(x => x.Employee)
   .WithMany(x => x.EmployeeCourses)
   .HasForeignKey(x => x.CourseId);

HasRequired(x => x.Course)
   .WithMany(x => x.EmployeeCourses)
   .HasForeignKey(x => x.EmployeeId);

来自Eagerly loading multiple levels

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method.

您可以这样尝试,因此它允许您加载所有 EmployeeCourses 和相关的 Courses

public IList<Course> GetEmployeeCourses(int id) {
  var employeeCourses = Context.Employees
    .Where(e => e.Id == id)
    .Include(e => e.employeeCourses.Select(ec => ec.Course))
    .SelectMany(e => e.employeeCourses.Select(ec => ec.Course))
    .ToList();

  return employeeCourses;
}

您可能喜欢使用链式 SelectMany 作为:

public IList<Course> GetEmployeeCourses(int id)
{
  var employeeCourses = Context.Employees
                        .Where(e => e.Id == id)
                        .SelectMany(e => e.employeeCourses
                        .SelectMany(ec => ec.Course))
                        .Include(c => c.Urls)
                        .ToList();



    return employeeCourses;
}