Linq to Entities中的动态where子句 [英] Dynamic where clause in Linq to Entities

查看:104
本文介绍了Linq to Entities中的动态where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用linq到实体(EF)。
我有一个构造函数,它需要4个字符串参数。根据什么参数不为空我必须构建linq查询。我可以使用if else语句,但是我也有其他的构造函数有10个参数,在这种情况下会有很多组合来检查。



示例:

 构造函数(p1,p2,p3,p4)
{
var prod = from ct in ctxt.products.expand( item\details)
其中px == p1&&& p.xx == p2&& p.xxx == p3&&& p.xxxx == p4
select p;
}

在上述where子句中,只有在参数不为空值。
ie。,
如果p2为null,那么where子句应该看起来像

 其中px == p1&& p.xxx == p3&&& p.xxxx == p4 

如果p2和p3为空,那么

 其中px == p1&&& p.xxxx == p4 

任何人都可以告诉我如何处理这个问题。如果可能,您可以提供此示例代码

解决方案

Linq的DeferredExecution以拯救。除非请求数据,否则不执行Linq查询。

  var prod = from ct in ctxt.products.expand( item \details)
选择p;

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

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

//执行查询

var prodResult = prod.ToList();


I'm using linq to entities(EF). I have a constructor which takes 4 string parameters. Depending on what parameter is not null I have to build the linq query. I can do with if else statements but i also has other constructor with 10 parameters in that case there will be many combinations to check.

Example:

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;
}

In the above where clause there should be condition checks only if the parameter is not null. ie., if p2 is null then the where clause should look like

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

if p2 and p3 are null then

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

Can anyone tell me how to handle this. if possible can you give sample code for this

解决方案

Linq's DeferredExecution to rescue. Linq query is not executed unless the data is requested from it.

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 to Entities中的动态where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆