【问题标题】:LINQ query to get all products with in Min & Max price range?LINQ 查询以获取最低和最高价格范围内的所有产品?
【发布时间】:2019-06-19 06:03:31
【问题描述】:

我想获取最低和最高价格范围内的所有产品。实际上,我正在传递一个包含价格范围的产品(对象),并通过获取其最小和最大价格值,我想从该范围内的数据库中获取所有产品。 我尝试过类似的方法:

public List<Products> SuggestedProducts(Product product)
{
    List<Product> products = (from c in db.Products.Include(x = > x.Category).Include(x = > x.User.CityId.Country).Include("Images")
                              where (c.MinPrice >= product.MinPrice) && (c.MinPrice <= product.MaxPrice)
                              where (c.MaxPrice <= product.MaxPrice) && (c.MaxPrice > product.MinPrice)
                              where (c.User.CityId.Id == product.User.CityId.Id)
                              where (c.User.Id != product.User.Id)
                              select c).ToList();

    return products;
}

在上面的代码中,我正在获取(或试图获取)所有那些介于我通过的产品范围之间的产品。 哪个工作不正常。我需要查询来获取我想要的产品

注意:我使用c.User.CityId.Id == product.user.CityId.Id 来获取相同位置的产品,并使用c.User.Id != product.user.Id 来跳过来自同一用户的产品。

【问题讨论】:

  • 问题是什么?
  • @RomanKoliada :以前的编辑删除该行。我提供的查询不起作用。我需要一个查询来获取范围内的所有产品。 (如上所述)
  • 您的查询看起来不错。尝试仔细检查表中是否有满足所有条件(userId、cityId 和价格范围)的产品。此外,查看生成的 sql 并在 SQL Server Management Studio 中手动运行它可能会很有用。
  • 你为什么用这么多where这么多次?
  • @FakharAhmadRasul 这些是让产品符合这些条件的条件。

标签: .net sql-server asp.net-mvc entity-framework linq


【解决方案1】:
List<Product> products = db.Products.Where(c => c.MinPrice >= product.MinPrice && c.MaxPrice <= product.MaxPrice && c.User.CityId.Id == product.User.CityId.Id && c.User.Id != product.User.Id);

【讨论】:

    【解决方案2】:

    只需使用单个 where 条件来获取价格

    where (c.MinPrice >= product.MinPrice && c.MaxPrice <= product.MaxPrice)
    

    【讨论】:

    • 数据库中有两个价格字段吗?
    • 是的。如代码所写,我有两个字段,最低价格和最高价格
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多