Left join usando Linq C#

Question:

I have the person table in which there are 100 people of which 80 are students, of those 80 only 50 are enrolled, I try to make a left join (Sql Server) to show me the student that exists, even when they are not enrolled

The table that stores the information of the course, parallel, shift is MATRICULA

var persona = (from p in db.Persona                                             // cantidad de Personas _________________________ 100
                join co in db.Colegio on p.CodColegio equals co.IdColegio        
                join al in db.Alumno on p.CodPersona equals al.CodPersona        // cantidad de personas que son alumnos___________ 80

                join ma in db.Matricula on al.CodAlumno equals ma.CodAlumno      // cantidad de añumnos que estan matriculados ___  50

                join cu in db.Curso on ma.CodCurso equals cu.CodCurso            // los _ 50 _ tienen curso asignado
                join pa in db.Paralelo on ma.CodParalelo equals pa.CodParalelo   // los _ 50 _ tienen paralelo asignado
                join tu in db.Turno on ma.CodTurno equals tu.CodTurno            // los _ 50 _ tienen turno asignado

                where p.NombreCompleto.ToUpper().Replace(" ", string.Empty) == nombre.ToUpper().Replace(" ", string.Empty)

                select new
                {
                    CodPersona       = p.CodPersona,
                    NombreCompleto   = p.NombreCompleto,

                    CodColegio       = p.CodColegio,
                    colegio          = co.Nombre,

                    curso            = cu.Descripcion,
                    paralelo         = pa.Descripcion,
                    turno            = tu.Descripcion
                }).FirstOrDefault();

Answer:

With the DefaultIfEmpty() method you can make a left join, I give you an example with Persona and Colegio

from p in db.Persona 
join co in db.Colegio on p.CodColegio equals co.IdColegio into PersonasColegio
from pco in PersonasColegio.DefaultIfEmpty()
select new {
    //lo que quieras seleccionar
}
Scroll to Top