簡體   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