Dave
Dave

Reputation: 166

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.

Upvotes: 1

Views: 749

Answers (2)

Jcl
Jcl

Reputation: 28272

You need to incude both levels:

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

Upvotes: 1

Engin Can
Engin Can

Reputation: 9

var teacher = await _context.Teacher.SelectMany(m=> m.TeacherClassroom).FirstOrDefaultAsync(m => m.Teacher_PK == id);

Can you try?

"The SelectMany() keyword creates a new collection as a result of combining the two collections according to the common fields"

Upvotes: 0

Related Questions