Dee*_*pak 10 linq entity-framework dynamic where-clause
我正在使用linq到实体(EF).我有一个构造函数,它接受4个字符串参数.根据什么参数不为null,我必须构建linq查询.我可以使用if else语句,但我也有其他10个参数的构造函数,在这种情况下,将有许多组合要检查.
例:
Constructor(p1,p2,p3,p4)
{
var prod= from p in ctxt.products.expand("items\details")
where p.x==p1 && p.xx==p2 && p.xxx==p3 && p.xxxx==p4
select p;
}
Run Code Online (Sandbox Code Playgroud)
在上面的where子句中,只有当参数不为null时才应该进行条件检查.即,如果p2为null,那么where子句应如下所示
where p.x==p1 && p.xxx==p3 && p.xxxx==p4
Run Code Online (Sandbox Code Playgroud)
如果p2和p3为null则
where p.x==p1 && p.xxxx==p4
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何处理这个问题.如果可能的话,你可以为此提供示例代码
ami*_*t_g 11
Linq的DeferredExecution进行救援.除非从中请求数据,否则不会执行Linq查询.
var prod = from p in ctxt.products.expand("items\details")
select p;
if (p1 != null)
{
prod = prod.Where(p => p.x == p1);
}
if (p2 != null)
{
prod = prod.Where(p => p.xx == p2);
}
// Execute the query
var prodResult = prod.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14046 次 |
| 最近记录: |