9

假设我有客户表,我想通过以下方式对其进行过滤:

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

如果我必须为这个过滤器构建一个 SQL 字符串,它会是这样的:

if (Country != "All") sql += "country = " + Country
if (Income != "All") sql += "and income = " + Income
if (Age != "All") sql += "and age = " + Age;

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

你如何使用实体框架来做到这一点?

谢谢 !

4

3 回答 3

25

LINQ to Entity queries return IQueryable's, so you can build your query this way:

IQueryable<Person> query = context.People;

if (Country != "All")
{
    query = query.Where(p => p.Country == Country);
}

if (Income != "All")
{
    query = query.Where(p => p.Income == Income);
}

if (Age != "All")
{
    query = query.Where(p => p.Age == Age);
}

List<Person> fetchedPeople = query.ToList();

This case is almost too simple, but this is very helpful in more complex situations when you need to add filtering dynamically.

于 2012-07-13T07:27:18.060 回答
12

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

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),则所有参数条件都为真,并且该参数不过滤结果。

于 2012-07-13T07:18:08.857 回答
0

您可以使用扩展方法来帮助代码的可读性和可维护性。

  • LinqExtensions.cs
public static class LinqExtensions
{
    public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
    {
        return condition ? source.Where(predicate) : source;
    }
}
  • 重构代码
List<Person> peoples = context.People
    .WhereIf(Country != "All", p => p.Country == Country)
    .WhereIf(Income != "All", p => p.Income == Income)
    .WhereIf(Age != "All", p => p.Age == Age)
    .ToList();
于 2021-11-29T03:01:16.303 回答