Home > database >  How to select only specific properties of navigation property
How to select only specific properties of navigation property

Time:02-24

I've got a simplify entity structure like the following:

class MarkingTask{
    List<Task_Student> task_Students
}
 
class Task_Student{
    List<Task_Student_Marker> task_Student_Markers
}

class Task_Student_Marker{
    User marker
}
class User{
   string name;
   int age;
   int password;
}

I am doing an eager loading like the following:

   var taskList = context.markingTasks
                .Include(mt => mt.task_Students)
                .ThenInclude(ts => ts.task_Student_Markers)
                .ThenInclude(tsm => tsm.marker) //Here, only want to select marker.name 
                .ToList();

The question is where can I do a select clause on the navigation property to select a few columns of interest? For instance, for now, all of the properties of User are being selected, but I just want the User.name.

I looked up the MSDN, it seems the select clause is not supported inside include clause. or I have to break it down into several statements.

Thanks for the tip

CodePudding user response:

Include and Select are two mutually exclusive things that can not be set simultaneously on the navigation object. In my case, they are all being interpreted as left Join, but Include will select all the properties in the navigation object. I ended up doing a few nested select to target properties of interset

         var mts = context.markingTasks.Where(mt => mt.rubric.moduleConvenor.emailAddress == email && mt.task_Students.Count() != 0)
            .Select(mt => new {
                    mt.name, 
                    mt.moduleCode, 
                    students = mt.task_Students.Select(ts => new { 
                                                                    ts.student.name,
                                                                    ts.student.studentId, 
                                                                    markers = ts.task_Student_Markers.Select(tsm=>tsm.marker.userName).ToList()}).ToList()}).ToList();
  • Related