Search code examples
c#sqllinqfilteringsql-to-linq-conversion

Linq query of left outer join not properly working


I converted sql query to linq query without any error.

Now, my question is that I get the data properly in sql query, while in linq query showing the whole data without filtering product null.

Here is my code:

SQL Query

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 

From this query data showing properly.

Linq Query

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();

Same query of linq showing whole data without filtering this (Where(x => x.Product == null)).

Is there a problem in linq syntax or in query?


Solution

  • Check with following query to return which has no product

    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 }