EF核心扩展,方法无效

时间:2019-10-25 22:39:18

标签: c# linq entity-framework-core extension-methods iqueryable

我为过滤器查询创建了新的IQueryable扩展方法。 在手动添加到我的查询的扩展方法内容中,它正在工作。 但是它不适用于IQueryable扩展方法。 怎么发生的?

我的扩展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;
    }

不起作用,此查询返回了所有数据:

MyDbContext.ProductPrices
           //.AsQueryable()
           .GetDynamicWhere(filter)
           .Include(x => x.ProductVariant.Product)
           .Include(x => x.ProductVariant.Variant)
           .Include(x => x.ProductVariant.Variant.VariantType)
           .ToList();

但这是可行的(GetDynamicWhere扩展方法中的相同代码):

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

1 个答案:

答案 0 :(得分:1)

Where和WhereIf子句不会更改源,而是返回IQueryable。您没有用这种价值做任何事情,而且它被扔掉了。然后,您返回原始来源。

相反,您可以执行以下操作:

kubectl