使用实体框架中的OR和Contains进行动态查询 [英] Dynamic query using OR and Contains in Entity Framework
问题描述
var filterOptions =First Bank;
还有一个具有Grantee列和Grantor列的表,如何使用EF创建查询这将产生以下where子句:
...其中(授予者喜欢'%First%'和Grantor like'%Bank %')或(受让人像'%First%'和受让人像'%Bank%')
请记住,filterOptions是一个传入的parm,所以它可以很容易地包含3或4个单词,而不仅仅是两个...在这种情况下,每个列都需要额外的类似子句。
如果不是OR的一部分,我会执行以下操作(这将有助于更好地了解我正在努力完成的任务。
foreach(filterOptions中的var word)
{
var text =%+ word +%;
query = query.Where(r => SqlMethods.Like(r.Grantee,text));
}
像我说的,它试图添加OR部分与另一个col
首先,阅读下面的博客,那么你将会知道如何做OR操作:
http://www.albahari.com/nutshell/predicatebuilder.aspx
其次,如果您使用实体框架,请阅读另一个博客,它对Entity Framework有更好的predicatebuilder实现:
http://petemontgomery.wordpress.com/2011/02/10/a-niversiversal- predicatebuilder /
Given a string like this:
var filterOptions = "First Bank";
And a table that has a Grantee column and a Grantor column, how do I create a query with EF that will generate the following where clause:
... where (Grantor like '%First%' and Grantor like '%Bank%') or (Grantee like '%First%' and Grantee like '%Bank%')
Keep in mind that filterOptions is a parm that is passed in, so it could just as easily contain 3 or 4 words rather than just two ... in which case each column would need additional like clauses.
If it weren't for the OR part of this, I would do the following (which will help give a better idea of what I'm trying to accomplish.
foreach(var word in filterOptions)
{
var text = "%" + word + "%";
query = query.Where(r => SqlMethods.Like(r.Grantee,text));
}
Like I said, its trying to add the OR portion with the other column that throws me for a loop.
First, Read the blog below, then you will know how to do the OR operation: http://www.albahari.com/nutshell/predicatebuilder.aspx
Second, If you're using Entity Framework, read another blog, it has a better "predicatebuilder" implematation for Entity Framework: http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/
这篇关于使用实体框架中的OR和Contains进行动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!