Include mapping table property reference with LINQ query


I have following Schema in EF Code First Architecture.

Class Teacher

public class Teacher
public int Teacher_PK { get; set; }
public string Name { get; set; }
public int Age { get; set; }        
public virtual ICollection<TeacherClassroom> TeacherClassroom { get; set; } // I have added this to access classroom class's property

Class Classroom

public class Classroom
public int Classroom_PK { get; set; }
public string ClassName { get; set; }
public int ClassStrength { get; set; }

I have made a table to establish relationship b/w those tables.

public class TeacherClassroom
public int TecherClassroom_PK { get; set; }

public virtual Teacher Teacher { get; set; }

public int Teacher_FK { get; set; }

public virtual Classroom Classroom { get; set; }

public int Classroom_FK { get; set; }

Now I want to access Classroom class’s property from Teacher class, for that I have added a virtual ICollection<TeacherClassroom> in Teacher class, but I can not get the data of classroom class’s property.

So far I have tried follwing

var teacher = await _context.Teacher.Include(c=>c.TeacherClassroom.Select(y=>y.Classroom))
                .FirstOrDefaultAsync(m => m.Teacher_PK == id);

In the above Sentence I am getting Classroom Property as null.

Thank You in Advance.

>Solution :

You need to incude both levels:

_context.Teacher.Include(c => c.TeacherClassroom)
                .ThenInclude(tc => tc.Classroom)
                .FirstOrDefaultAsync(m => m.Teacher_PK == id);

Leave a ReplyCancel reply