EF Core 开发实践:Left Join 查询的多种实现方式

本文记录了使用 efcore 中多种左连接查询的写法。

场景示例

  • 订单表:Order
  • 订单明细表:OrderItem,可以为空
csharp 复制代码
public class Order
{
    public int Id { get; set; }
    public string OrderNo { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }
    public string ProductName { get; set; }
}

一、LINQ 查询语法

csharp 复制代码
var query =
    from o in context.Orders
    join oi in context.OrderItems on o.Id equals oi.OrderId
        into items
    from oi in items.DefaultIfEmpty()
    select new
    {
        o.OrderNo,
        ProductName = oi != null ? oi.ProductName : null
    };

二、Linq方法语法(GroupJoin + SelectMandy)

csharp 复制代码
var query = context.Orders
    .GroupJoin(
        context.OrderItems,
        o => o.Id,
        oi => oi.OrderId,
        (o, items) => new { o, items }
    )
    .SelectMany(
        x => x.items.DefaultIfEmpty(),
        (x, oi) => new
        {
            x.o.OrderNo,
            ProductName = oi != null ? oi.ProductName : null
        }
    );

三、导航属性

模型已配置导航属性:

csharp 复制代码
public class Order
{
    public int Id { get; set; }
    public string OrderNo { get; set; }
    
    public ICollection<OrderItem> OrderItems { get; set; }
}

查询写法:

csharp 复制代码
var query = context.Orders.Select(o => new
{
    o.OrderNo,
    o.OrderItems
});

以上就是 ef core 左连接的三种查询写法。

相关推荐
苏supper11 小时前
Spring Boot多环境配置与打包运行
spring boot·后端·spring
geovindu11 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
SearchMan12 小时前
还有人不知道&和&&的区别?
后端
想用offer打牌12 小时前
Personal Agent爆火 - 它到底是个什么
人工智能·后端·ai编程
IT_陈寒12 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
打工仔折腾 AI14 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert
lizhongxuan15 小时前
Agent Sandbox: Firecracker 任务生命周期
后端
YYYing.15 小时前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式
lizhongxuan16 小时前
Agent Sandbox: Firecracker 镜像、启动与 I/O
后端
打工仔折腾 AI17 小时前
飞牛OS上用Docker Compose部署ExerciseDiary运动记录并配置远程访问
运维·人工智能·后端·python·docker·容器·ai agent 实战