Linq - Search for objects that have a pre-determined list

3

I have a many-to-many entity, many students for many subjects. And I need to get all the students who have all the materials I want.

For example, subjects: Mathematics, Portuguese and Physics. I need to get only the students who have these three subjects. If he has other matter, but he has these three, that's fine. If he has only one or two of the subjects in question, disregard it, it will not do.

My relationship table is as follows:

tbAlunosMaterias
AlunoId
MateriaId

Is it possible to get this information through linq or lambda? Something like:

var alunosDasMaterias = alunos.Contains(x => ... );

Where: students = list of all students with their respective subjects       (x) = where I inform the list of subjects that the student must have

    
asked by anonymous 20.01.2016 / 17:36

1 answer

2

You need to have mapped the association between Students and Subjects in their context:

public DbSet<AlunoMateria> AlunosMaterias { get; set; }

The sentence would look like this:

var idsDasMaterias = new int[] { 1, 2, 3 }; // Não sei quais são os Ids, então estou chutando Ids para as matérias
var alunosDasMaterias = contexto.AlunosMaterias
                                .Where(am => idsDasMaterias.Contains(am.MateriaId))
                                .Select(am => am.Aluno)
                                .ToList();
    
20.01.2016 / 17:50