动态where子句在LINQ - 与在运行时可用列名 [英] Dynamic where clause in LINQ - with column names available at runtime

查看:92
本文介绍了动态where子句在LINQ - 与在运行时可用列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我已经解决了使用防爆pressions从System.Linq.Ex pressions这个问题,但我仍然在寻找更好/更简单的方法

Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.

考虑以下情况:

var query = 
    from c in db.Customers
    where (c.ContactFirstName.Contains("BlackListed") || 
           c.ContactLastName.Contains("BlackListed")  ||
           c.Address.Contains("BlackListed"))
    select c;

列/只提供给我在运行时需要进行对列入黑名单的期限检查属性。如何生成这个充满活力的where子句?

The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?

另外一个复杂的是,可查询集合(db.​​Customers以上)被输入到'客户'的基类的可查询(说'人'),因此写c.Address如上是不是一种选择。

An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.

推荐答案

@Geoff拥有最好的选择,justing动态LINQ。

@Geoff has the best option, justing Dynamic LINQ.

如果你想使用lambda去建立查询的方式在运行时,虽然我会电子书籍您使用predicateBuilder(<一href="http://www.albahari.com/nutshell/$p$pdicatebuilder.aspx">http://www.albahari.com/nutshell/$p$pdicatebuilder.aspx)而有一些像这样的:

If you want to go the way of building queries at runtime using Lambda though I'd recomment that you use the PredicateBuilder (http://www.albahari.com/nutshell/predicatebuilder.aspx) and have something such as this:

Expression<Fun<T,bool>> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T 
if(blacklistFirstName){
  pred = p => p.ContactFirstName.Contains("Blacklisted");
}
if(blacklistLastName){
  if(pred == null){
    pred = p => p.ContactLastName.Contains("Blacklisted"); //if it doesn't exist just assign it
  }else{
    pred = pred.And(p => p.ContactLastName.Contains("Blacklisted"); //otherwise we add it as an And clause
  }
}

等了所有你要包含的列。当你到你的查询,你只需要像这样:

And so on for all the columns you want to include. When you get to your query you just need something like this:

var results = db.Customers.Where(pred).Select(c => c);

我用这个做LINQ的建设进行搜索,其中有大约20个不同的选项,它会产生真正的好SQL。

I've used this to do building of LINQ for searching where there are about 20 different options and it produces really good SQL.

这篇关于动态where子句在LINQ - 与在运行时可用列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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