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

如何在EF Linq中改写含OR条件的INNER JOIN语句?

将带OR连接条件的TSQL转换为EF LINQ语句

原TSQL的核心逻辑是:对InventoryTypeProductTypeMapping(简称ITM)与Product表执行内连接,当Product的ProductCategoryId匹配ITM.ProductCategoryId(空值替换为0),或者Product的ProductTypeId匹配ITM.ProductTypeId(空值替换为0)时返回匹配项,最终提取Product.Id作为结果。

以下是两种EF LINQ实现方式:

查询语法(直观对应原SQL结构)

var query = from itm in dbContext.InventoryTypeProductTypeMapping
            from p in dbContext.Product
            where (p.ProductCategoryId == (itm.ProductCategoryId ?? 0)) || 
                  (p.ProductTypeId == (itm.ProductTypeId ?? 0))
            select new { ProductId = p.Id };

方法语法

var query = dbContext.InventoryTypeProductTypeMapping
    .SelectMany(
        itm => dbContext.Product
            .Where(p => p.ProductCategoryId == (itm.ProductCategoryId ?? 0) || 
                        p.ProductTypeId == (itm.ProductTypeId ?? 0)),
        (itm, p) => new { ProductId = p.Id }
    );

注意事项

  • 若InventoryTypeProductTypeMapping的ProductCategoryId/ProductTypeId是可空值类型(如int?),?? 0等价于SQL中的ISNULL(..., 0);若数据库字段默认值为0而非NULL,可移除?? 0。
  • 两种写法都会被EF Core解析为与原TSQL逻辑一致的SQL查询,生成带OR条件的内连接语句。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:33:12