简体   繁体   English

在 EF 6 LINQ 中使用 Include() 左连接

[英]Left join using Include() in EF 6 LINQ

I am using Include() method in LINQ to join two tables (Student and StudentLibrary) with StudentId as foreignKey.我在 LINQ 中使用Include()方法来连接两个表(Student 和 StudentLibrary),StudentId 作为foreignKey。 It is working as inner join, however I need to do the left join using Include().它作为内连接工作,但是我需要使用 Include() 进行左连接。

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

Below is my model下面是我的 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 . Student实体映射到StudentModel The case where a student does not have StudentLibrary details, the Include() method does not return that record and act as inner join.如果学生没有 StudentLibrary 详细信息,则 Include() 方法不会返回该记录并充当内部联接。 How can I make Include() behave as left join.如何使 Include() 表现为左连接。 I tried using DefaultIfEmpty() but its not working.我尝试使用 DefaultIfEmpty() 但它不起作用。

The link shared by Timothy G. does have an answer. Timothy G. 共享的链接确实有答案。

You should set the foreign key as nullable on both the database table and the entity class.您应该在数据库表和实体 class 上将外键设置为可为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM