实体框架:条件过滤器 [英] entity framework: conditional filter
本文介绍了实体框架:条件过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有Customers表,我想通过以下方式过滤:
- 国家:美国,英国,加拿大
- 收入:全部,低,高,中
- 年龄:所有,青少年,成人 ul>
如果我必须为此过滤器构建一个SQL字符串,它将是这样:
if(Country!=All)sql + =country =+ Country
if(Income!=All)sql + =and income =+ Income
if(Age!=All)sql + =and age =+ Age;
因此,基本上,用户可以筛选一些,但不是必要的所有字段。
$ b
谢谢!
解决方案
您可以通过这种方式包含条件参数:
return Customers.Where b $ b customer =>
customer.Name == Name&
(Age ==All|| customer.Age == Age)&&
Income ==All|| customer.Income == Income)&&
(Country ==All|| customer.Country == Country)
).ToList();
如果某些条件为真(例如country等于 All
),那么所有参数条件变为true,并且此参数不过滤结果。
Let's say I have Customers table and I want to filter it by the following:
- Country: All, US, UK, Canada
- Income: All, low, high, medium
- Age:All, teenager, adult, senior
if I had to build an SQL string for this filter, it would be something like this:
if (Country != "All") sql += "country = " + Country
if (Income != "All") sql += "and income = " + Income
if (Age != "All") sql += "and age = " + Age;
So, basically, the user can filter by some, but not necessary all fields.
How do you do this using Entity Framework ?
Thanks !
解决方案
You can include conditional parameter this way:
return Customers.Where(
customer =>
customer.Name == Name &&
(Age == "All" || customer.Age == Age) &&
(Income == "All" || customer.Income == Income) &&
(Country == "All" || customer.Country == Country)
).ToList();
If some condition is true (e.g. country is equal to All
), then all parameter condition becomes true, and this parameter does not filter result.
这篇关于实体框架:条件过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文