Search code examples
c#entity-frameworklinqentity-framework-6

Entity Framework filter nested collection


I have a entity relation diagram as follows.

ClassEntity:

public int id
public int std
public virtual ICollection<StudentEntity> students

StudentEntity:

public int id
public string name
public string gender
public virtual ClassEntity class
public virtual StudentAddressEntity studentAddress

StudentAddressEntity:

public int id
public string address

I need to get the class and its male children.

var classEntity = dbContext.Set<ClassEntity>().Where(t => t.id == classId);
var query = classEntity.Include(c => c.students.Select(s => s.studentAddress))
           .FirstOrDefault(c => c.students.Any(s => s.gender == GenderEnum.Male));

But it is returning the class with all the students. How to filter only male students?


Solution

  • The below should load only the male students for each class.

    var classEntity = testContext.Set<ClassEntity>().Where(t => t.Id == classId);
    var classes = classEntity.ToList().Select(c =>
    {
        testContext.Entry(c)
        .Collection(p => p.Students)
        .Query()
        .Where(s => s.Gender == GenderEnum.Male)
        .Load();
    
        return c;
    });