This query works until filter.Exported and filter.Ordered are null but when they are true or false, it returns unexpected items and I don’t know why
public List<ProductResponse> GetProducts(ProductFilter filter)
{
List<ProductResponse> products = _db.Products
.Include(db => db.ProductType)
.ThenInclude(product => product.ProductCategory)
.Where(product => string.IsNullOrEmpty(filter.ProductTypeId.ToString()) || product.ProductTypeId.ToString().Contains(filter.ProductTypeId.ToString()))
.Where(product => string.IsNullOrEmpty(filter.ProductCategoryId.ToString())
|| product.ProductType.ProductCategoryId.ToString().Contains(filter.ProductCategoryId.ToString()))
.Where(product => !filter.Ordered.HasValue || (bool)filter.Ordered
? _db.OrderedProducts.Any(orderedProduct => orderedProduct.ProductId == product.Id)
: !_db.OrderedProducts.Any(orderedProduct => orderedProduct.ProductId == product.Id))
.Where(product => !filter.Exported.HasValue || (bool)filter.Exported ? product.ExportDate != null : product.ExportDate == null)
.Where(product => string.IsNullOrEmpty(filter.ProductionDateFrom.ToString()) || product.ProductionDate >= filter.ProductionDateFrom)
.Where(product => string.IsNullOrEmpty(filter.ProductionDateTo.ToString()) || product.ProductionDate <= filter.ProductionDateTo)
.Where(product => string.IsNullOrEmpty(filter.ExportDateFrom.ToString()) || product.ExportDate >= filter.ExportDateFrom)
.Where(product => string.IsNullOrEmpty(filter.ExportDateTo.ToString()) || product.ExportDate <= filter.ExportDateTo)
.Select(product => new ProductResponse
{
Id = product.Id,
ProductCategoryId = product.ProductType.ProductCategoryId,
ProductCategoryName = product.ProductType.ProductCategory.CategoryName,
ProductTypeId = product.ProductTypeId,
ProductTypeName = product.ProductType.TypeName,
ProductionDate = product.ProductionDate,
ExportDate = product.ExportDate
})
.ToList();
return products;
}
I’ve tried the string.IsNullOrEmpty approach but I had the same result