You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在EntityFramework Core中用Lambda实现类似SQL的CASE逻辑?

使用EntityFramework Core Lambda表达式实现目标SQL查询

原SQL的逻辑是计算Inventories表中,当OperationType为1时累加ProductCountMain,为2时累减ProductCountMain的总和,其他类型的记录不参与计算。对应的EF Core Lambda实现如下:

实现代码(C# 8.0+ 推荐写法)

var result = dbContext.Inventories
    .Sum(inventory => inventory.OperationType switch
    {
        1 => inventory.ProductCountMain,
        2 => -inventory.ProductCountMain,
        _ => null // 对应SQL中CASE未匹配的情况,Sum会忽略null值
    });

兼容旧版C#的写法(嵌套三元运算符)

var result = dbContext.Inventories
    .Sum(inventory => 
        inventory.OperationType == 1 ? inventory.ProductCountMain : 
        inventory.OperationType == 2 ? -inventory.ProductCountMain : null);

说明

  • Sum方法直接对应SQL中的SUM函数,传入的表达式对应原SQL里的CASE WHEN逻辑。
  • 当OperationType不属于1或2时,返回null,EF Core生成的SQL会和原SQL一致,忽略这些记录的计算。
  • 返回值类型为int?(假设ProductCountMain是int类型),如果需要非 nullable 类型,可以根据业务场景调用result.GetValueOrDefault()或确保存在匹配记录后强制转换。

内容的提问来源于stack exchange,提问作者hamid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:39:24