【问题标题】:EF Core Extension Where Method Not Working [closed]EF Core Extension where方法不起作用[关闭]
【发布时间】:2020-02-22 06:43:07
【问题描述】:

我为过滤查询创建了新的 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();

【问题讨论】:

  • 您没有在您的方法中分配回源GetDynamicWhere

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


【解决方案1】:

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

相反,您可以这样做:

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

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 2021-05-07
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多