简体   繁体   English

EF Core 3.1 中的 Include / ThenInclude 如何转化为 Inner Join

[英]How Include / ThenInclude in EF Core 3.1 Will Be transformed as Inner Join

I am using EF Core 3.1.我正在使用 EF Core 3.1。 I want Include() and ThenInclude to Produce Inner join But They are producing LEFT join .我希望 Include() 和 ThenInclude 产生Inner join但他们正在产生 LEFT join 。 I am using Code-First approach.我正在使用代码优先方法。 Following are my Sample Model以下是我的示例模型

public class Employee
    {
        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

        public string Gender { get; set; }

        public string Img1 { get; set; }

        public virtual EmployeeDepartment EmployeeDepartment { get; set; }
    }

And
    public class EmployeeDepartment
    {       
        public int DeptID { get; set; }

        [ForeignKey("Employee")]
        [Required]
        public int Id { get; set; }

        public string DeptName { get; set; }

        public virtual Employee Employee { get; set; }
    }

Following is the linq Query以下是linq查询

var result= context.Employees.Include(dept => dept.EmployeeDepartment).ToList();

Which produces below Sql query in O/P window在 O/P 窗口中产生下面的 Sql 查询

SELECT [dept].[Id], [dept].[Gender], [dept].[Img1], [dept].[Name], [dept.EmployeeDepartment].[Id], [dept.EmployeeDepartment].[DeptID], [dept.EmployeeDepartment].[DeptName]
FROM [Employees] AS [dept]
**LEFT JOIN** [EmployeeDepartment] AS [dept.EmployeeDepartment] ON [dept].[Id] = [dept.EmployeeDepartment].[Id]

I want inner join to be produced .Any Suggestions are welcome.我想要产生内连接。欢迎提出任何建议。

You could try reverting the order of the query(eg child -> parent):您可以尝试恢复查询的顺序(例如 child -> parent):

var result= _context.EmployeeDepartments.Include(dept => dept.Employee).ToList();

However that adds additional mental overhead and may not be what you are looking for.然而,这会增加额外的心理开销,可能不是您想要的。 If your relationship is required in your domain model I would suggest sticking with your query, it shouldn´t impact performance because left and inner join in this case will give the same result.如果您的域模型中需要您的关系,我建议您坚持使用您的查询,它不应该影响性能,因为在这种情况下左连接和内连接将给出相同的结果。

PS: For the EmployeeDepartment class you configured Id as both the primary key(by convention) and foreign key(with data annotation). PS:对于 EmployeeDepartment 类,您将 Id 配置为主键(按照约定)和外键(带数据注释)。 The DeptID property is not being used(which I guess was intended to be the PK).未使用 DeptID 属性(我猜它是用来作为 PK 的)。

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

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