LINQ Включить дочерний массив выбора - PullRequest
3 голосов
/ 01 марта 2020

У меня есть следующий 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) выбранного курса при возврате массива Course.

Что-то вроде:

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);

Ответы [ 2 ]

2 голосов
/ 02 марта 2020

С Стремительная загрузка нескольких уровней :

Стремительная загрузка - это процесс, при котором запрос для одного типа объекта также загружает связанные объекты как часть запроса. Быстрая загрузка достигается с помощью метода Include.

Вы можете попробовать вот так, поэтому он позволяет загружать все 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;
}
1 голос
/ 02 марта 2020

Вы можете использовать цепочку 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...