利用EF Core的Join进行多表查询

背景

话说有这么一家子,老公养了一条狗,老婆养了一只猫。

数据库的设计

人表
在这里插入图片描述
宠物表
在这里插入图片描述
通过表可以知道,宠物通过Owner指向主人的Id

问题来了,我要和故事开头一样,老公-狗,老婆-猫,对应起来,怎么查询呢?

有同学说这还不简单?两个遍历一下不就行了。

首先 取出 List<宠物>集合,再根据宠物的主人Id去查找对应的主人信息就好了。

如果这样设计,那么将会执行3次查询:

l 查出所有的宠物。

l 查出阿猫的主人。

l 查出阿狗的主人。

数据量不大还好,数据量要是大一点这是非常影响速度的。这时,我们可以用到EF Core所有的Join方法进行多表查询。

我的做法是定义了一个PetsDetails的类,其代码如下:

  public class PetsDetails
    {
        /// <summary>
        /// 宠物名称
        /// </summary>
        public string PetName { get; set; }
        /// <summary>
        /// 主人名称
        /// </summary>
        public string OwnerName { get; set; }
    }

用EF 的Join方法进行多表查询:

[HttpGet]
public List<PetsDetails> Get()
{
    return _context.Pets.Join(_context.Persons,pet=>pet.Owner,per=>per.Id,(pet,per)=>new PetsDetails
    {
        PetName = pet.Name,
        OwnerName = per.Name
    }).ToList();
}

执行结果如图:
在这里插入图片描述
成功取到了宠物对应的主人的名称。

好处

原本需要进行3次查询的,用了Join方法后一次查询即可取到所需要的结果。我们看看这条Sql语句的样子:
在这里插入图片描述
我们看到其实这个需求是EF通过再sql语句中执行INNER JOIN实现的。

完整项目代码:

https://github.com/liuzhenyulive/EF-CORE-JOIN-Demo

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Entity Framework Core (EF Core) allows you to perform inner join operation between two or more tables using LINQ queries or query syntax. Here is an example of performing inner join using LINQ queries: ```csharp var result = from emp in context.Employees join dept in context.Departments on emp.DepartmentId equals dept.DepartmentId select new { EmployeeName = emp.Name, DepartmentName = dept.Name }; ``` In this example, we are joining two tables `Employees` and `Departments` based on the `DepartmentId` column. The result will contain a collection of anonymous objects with properties `EmployeeName` and `DepartmentName`. Here is an example of performing inner join using method syntax: ```csharp var result = context.Employees .Join(context.Departments, emp => emp.DepartmentId, dept => dept.DepartmentId, (emp, dept) => new { EmployeeName = emp.Name, DepartmentName = dept.Name }) .ToList(); ``` In this example, we are performing inner join using `Join` method. We are passing four parameters to the `Join` method - first parameter is the inner collection (`context.Departments`), second parameter is the outer collection (`context.Employees`), third parameter is the key selector for the inner collection (`dept => dept.DepartmentId`), fourth parameter is the key selector for the outer collection (`emp => emp.DepartmentId`), and the fifth parameter is the result selector (`(emp, dept) => new {...}`). The `ToList()` method is used to execute the query and return the results as a list. I hope this helps! Let me know if you have any further questions.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值