实体框架:条件过滤器

Dav*_*vid 7 entity-framework c#-4.0

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

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

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

if (Country != "All") sql += "country = " + Country
if (Income != "All") sql += "and income = " + Income
if (Age != "All") sql += "and age = " + Age;
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢 !

Yak*_*ych 21

LINQ to Entity查询返回IQueryable,因此您可以这样构建查询:

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();
Run Code Online (Sandbox Code Playgroud)

这种情况几乎太简单了,但是当您需要动态添加过滤时,这在更复杂的情况下非常有用.


Ser*_*kiy 9

您可以这样包含条件参数:

return Customers.Where(
                customer =>
                customer.Name == Name &&
                (Age == "All" || customer.Age == Age) &&
                (Income == "All" || customer.Income == Income) &&
                (Country == "All" || customer.Country == Country)
                ).ToList();
Run Code Online (Sandbox Code Playgroud)

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