gpt4 book ai didi

linq - Linq to Entities中的动态where子句

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

我正在使用linq to实体(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;
}

在上述where子句中,仅当参数不为null时才应进行条件检查。
IE。,
如果p2为null,则where子句应如下所示
where p.x==p1 && p.xxx==p3 && p.xxxx==p4

如果p2和p3为空,则
where p.x==p1 && p.xxxx==p4

谁能告诉我该如何处理。如果可能的话,您能否为此提供示例代码

最佳答案

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();

关于linq - Linq to Entities中的动态where子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9122220/

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