Linq左外部联接的查询无法正常工作

问题描述

我将 sql 查询转换为 linq 查询,而没有任何错误

现在,我的问题是我可以在SQL查询中正确获取数据,而在linq查询显示整个数据而不过滤产品null

这是我的代码

SQL查询

SELECT Name
FROM ProductMaster product
LEFT JOIN TouchWastageGroup touchWastageGroup ON touchWastageGroup.Product = product.Name and touchWastageGroup.GroupNameId = 2 and touchWastageGroup.CaratId = 6
WHERE touchWastageGroup.Product IS NULL 

查询数据显示正确。

Linq查询

var productSelected = (from product in _productMasterRepository.Table
from touchWastageGroup in _touchWastageGroupRepository.Table
.Where(touchWastageGroup => touchWastageGroup.Product == product.Name && touchWastageGroup.GroupNameId == 2 && touchWastageGroup.CaratId == 6)                                   
.DefaultIfEmpty().Where(x => x.Product == null)
select new
{
   Result = product.Name
}).ToList();

对linq的同一查询显示了整个数据而不对其进行过滤(其中(x => x.Product == null))。

linq语法或查询是否存在问题?

解决方法

检查以下查询以返回没有产品的

from product in _productMasterRepository.Table
join touchWastageGroup in _touchWastageGroupRepository.Table on new { Product = product.Product,GroupNameId = 2,CaratId = 6 } equals new { touchWastageGroup.Product,touchWastageGroup.GroupNameId,touchWastageGroup.CaratId } into joinedResult
from touchWastageGroup in joinedResult.DefaultIfEmpty()
where touchWastageGroup == null
select new { Result = product.Name }
,

尝试使用此查询

var productSelected = from product in _productMasterRepository.Table
join from touchWastageGroup in _touchWastageGroupRepository.Table on
product.Name equals touchWastageGroup.Product into temp
from t in temp.DefaultIfEmpty()
where t.GroupNameId == 2 && t.CaratId == 6
select new
{
   Result = product.Name
}).ToList();