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

