Linq to Entities中的动态where子句

时间:2012-02-03 00:44:09

标签: 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;
}

在上面的where子句中,只有当参数不为null时才应该进行条件检查。 即, 如果p2为null,那么where子句应该看起来像

where p.x==p1 && p.xxx==p3 && p.xxxx==p4

如果p2和p3为空则

where p.x==p1 && p.xxxx==p4

任何人都可以告诉我如何处理这个问题。如果可能,您可以为此

提供示例代码

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:3)

您可以根据需要链接方法:

 YourType(string p1, string p2, string p3, string p4)
 {
      var prod = ctxt.Products.Expand("items\details");

      if (!p1.IsNullOrWhiteSpace())
          prod = prod.Where(p => p.x == p1);
      if (!p2.IsNullOrWhiteSpace())
          prod = prod.Where(p => p.xx == p2);

      // ....

      // use "prod"
 }

生成的SQL应该与将它们全部放在一个语句中相同。

答案 2 :(得分:3)

您总是可以分段构建查询并利用延迟查询执行:

public Constructor(int? p1, int? p2, int? p3, int? p4)
{
    var prod = ctxt.products.expand("items\details");

    if(p1 != null)
        prod = prod.Where(p.x == p1);

    if(p2 != null)
        prod = prod.Where(p.xx == p2);

    if(p3 != null)
        prod = prod.Where(p.xxx == p3);

    if(p4 != null)
        prod = prod.Where(p.xxxx == p4);
}