Search code examples
c#entity-framework-coreef-code-first-mapping

Include mapping table property reference with LINQ query


I have following Schema in EF Code First Architecture.

Class Teacher

public class Teacher
{
[Key]
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
{
[Key]
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
{
[Key]
public int TecherClassroom_PK { get; set; }

[ForeignKey("Teacher_FK")]
public virtual Teacher Teacher { get; set; }

[Required]
public int Teacher_FK { get; set; }

[ForeignKey("Classroom_FK")]
public virtual Classroom Classroom { get; set; }

[Required]
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);