Linq.SQL文本字段与值列表进行比较 [英] Linq.Where-to-SQL on a text field comparing to a list of values
问题描述
Customer.text是T-SQL DB(我不控制,因此可能不会更改)中的一个字段,其类型为文本".
Customer.text is a field in an T-SQL DB (that I do not control and thus may not alter) of type "text".
我想做这样的事情:
List<string> compare = new List<string>();
compare.Add("one");
compare.Add("two");
var q = from t in customer
where t.text.Contains( compare.First())
select t;
这将起作用.
但是现在我想做类似的事情:(!不工作!)
But now I'd like to do something like: (!NOT WORKING!)
var q = from t in customer
where compare.Contains( t.text )
select t;
我该如何实现?甚至有可能吗?
How can I achieve this? Is it even possible?
问题显然不能完全解决:SQL中的文本列不能使用"="来查询,而只能使用LIKE来查询.因此,compare.Contains(t.text)将导致错误,因为它会使用"="转换为查询.
The problem is obviously not exactly clear: A text column in SQL cannot be queried using "=" but only with LIKE. Thus the compare.Contains( t.text ) will result in an error, as it is converted into a query using "=".
我没有告诉我的-我认为这无关紧要-是我使用LINQ-to-ORM(在这种情况下为LLBLGen). 我尝试了什么:
What I did not tell - I thought it is irrelevant - is, that I use LINQ-to-ORM (LLBLGen in this case). What I tried instead:
var q = from t in customer
where compare.Any( x => t.text.Contains(x) )
select t;
现在这也不起作用.目前,我不在上班,但是有一个例外,就是ConstantExpression无法转换为SetExpression.
Now this did not work also. Currently I'm not at work, but the exception was something with a ConstantExpression not being convertable into a SetExpression.
我希望这可以澄清一下.
I hope this gave some clarification.
Joseph向我指出了这一点: PredicateBuilder .它在给定的ObjectType上创建一个Expression. 现在的问题是,我的类型是多个联接中的匿名类型. 有没有简单或优雅的方式来处理此问题?
Joseph pointed this out to me: PredicateBuilder. It creates an Expression on a given ObjectType. Now my problem is, that my type is an anonymous type out of multiple joins. Is there an easy or elegant way to handle this?
推荐答案
您可以使用LinqKit的免费谓词构建器类来构建查询.这是一篇博客文章,描述了其用法,并具有指向下载站点的链接.
You could build your query using LinqKit's free predicate builder class. Here is a blog post which describes its use and has a link to the download site.
http://thecodeslinger.wordpress.com/2008/10/28/linqkit-predicatebuildert-goodness/
下面是帖子中的代码示例
Below is a code sample from the post
//First get a list of keywords that match the description entered.
string[] parts = txtInclude.Text.Split(new[] {‘ ‘});
string[] noparts = null;
if(txtButNot.Text.Trim().Length > 0)
noparts = txtExclude.Text.Trim().Split(new[] {‘ ‘});
var pred = PredicateBuilder.True<Pet>();
//here is where you would loop through your compare object
parts.ForEach(p => pred = pred.And(pl => pl.description.Contains(p)));
if(noparts != null)
noparts.ForEach(p => pred = pred.And(pl => !pl.description.Contains(p)));
var pets = from s in db.Pets.Where(pred)
select s;
这篇关于Linq.SQL文本字段与值列表进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!