I created new IQueryable extension method for my filter queries. In the extension method content added to my query manually, it is working. But its not working on the IQueryable extension method. How that happens ?
My Extension IQueryables :
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static IQueryable<ProductPrice> GetDynamicWhere(this IQueryable<ProductPrice> source,List<ProductFilterModel> productFilters)
{
Func<string, object> GetValue = (string key) => productFilters.Where(y => y.key == key).Select(x => x.value).FirstOrDefault();
var minPrice = GetValue("min-price");
var maxPrice = GetValue("max-price");
source.Where(x=>x.IsDeleted==false)
.WhereIf(minPrice != null, x => x.ProductVariant.ProductPrices.Where(y => y.IsDeleted == false).Select(y => y.Price).FirstOrDefault() >= Convert.ToInt32(minPrice.ToString()))
.WhereIf(maxPrice != null, x => x.ProductVariant.ProductPrices.Where(y => y.IsDeleted == false).Select(y => y.Price).FirstOrDefault() <= Convert.ToInt32(minPrice.ToString()));
return source;
}
not working,this query returned all data:
MyDbContext.ProductPrices
//.AsQueryable()
.GetDynamicWhere(filter)
.Include(x => x.ProductVariant.Product)
.Include(x => x.ProductVariant.Variant)
.Include(x => x.ProductVariant.Variant.VariantType)
.ToList();
But this is working (same code in the GetDynamicWhere extension method) :
MyDbContext.ProductPrices
.Where(x=>x.IsDeleted==false)
.WhereIf(minPrice != null, x => x.ProductVariant.ProductPrices.Where(y => y.IsDeleted == false).Select(y => y.Price).FirstOrDefault() >= Convert.ToInt32(minPrice.ToString()))
.WhereIf(maxPrice != null, x => x.ProductVariant.ProductPrices.Where(y => y.IsDeleted == false).Select(y => y.Price).FirstOrDefault() <= Convert.ToInt32(minPrice.ToString()))
.ToList();