繁体   English   中英

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

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

我在 LINQ 中使用Include()方法来连接两个表(Student 和 StudentLibrary),StudentId 作为foreignKey。 它作为内连接工作,但是我需要使用 Include() 进行左连接。

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

下面是我的 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;}
}

Student实体映射到StudentModel 如果学生没有 StudentLibrary 详细信息,则 Include() 方法不会返回该记录并充当内部联接。 如何使 Include() 表现为左连接。 我尝试使用 DefaultIfEmpty() 但它不起作用。

Timothy G. 共享的链接确实有答案。

您应该在数据库表和实体 class 上将外键设置为可为空。

暂无
暂无

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

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