如何在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
相关产品推荐
相关产品推荐

