gpt4 book ai didi

entity-framework - Entity Framework : conditional filter

转载 作者:行者123 更新时间:2023-12-04 08:30:35 24 4
gpt4 key购买 nike

假设我有客户表,我想按以下方式过滤它:

  • 国家:全部、美国、英国、加拿大
  • 收入:全部、低、高、中
  • 年龄:所有、青少年、成人、老年人

  • 如果我必须为这个过滤器构建一个 SQL 字符串,它会是这样的:
    if (Country != "All") sql += "country = " + Country
    if (Income != "All") sql += "and income = " + Income
    if (Age != "All") sql += "and age = " + Age;

    因此,基本上,用户可以按某些字段进行过滤,但不是必须的所有字段。

    你如何使用 Entity Framework 做到这一点?

    谢谢 !

    最佳答案

    您可以通过以下方式包含条件参数:

    return Customers.Where(
    customer =>
    customer.Name == Name &&
    (Age == "All" || customer.Age == Age) &&
    (Income == "All" || customer.Income == Income) &&
    (Country == "All" || customer.Country == Country)
    ).ToList();

    如果某些条件为真(例如 country 等于 All ),则所有参数条件都为真,并且此参数不会过滤结果。

    关于entity-framework - Entity Framework : conditional filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11465772/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com