Left join using Include() in EF 6 LINQ

Viewed 39

I am using Include() method in LINQ to join two tables (Student and StudentLibrary) with StudentId as foreignKey. It is working as inner join, however I need to do the left join using Include().

var result = dbcontext.Student
             .Include(x=> x.StudentLibrary).DefaultIfEmpty() 
             .Select(x=> Mapper.Map<StudentModel>(x))
             .ToListAsync();

Below is my model

public class StudentModel
{
     public int Id {get; set;}

     public string Name {get; set;}

     public StudentLibraryModel StudentLibraryInfo {get; set;}
}

[Table("Student")]
public class Student
{
     [key]
     public int Id {get; set;}

     public string Name {get; set;}

     [ForeignKey("StudentId")
     public StudentLibrary StudentLibraryInfo {get; set;}
}

The Student entity is mapped to StudentModel. The case where a student does not have StudentLibrary details, the Include() method does not return that record and act as inner join. How can I make Include() behave as left join. I tried using DefaultIfEmpty() but its not working.

1 Answers

The link shared by Timothy G. does have an answer.

You should set the foreign key as nullable on both the database table and the entity class.

Related