LINQ到实体(EF 4.1):如何做一个SQL LIKE在中​​间(“%长期%长期%')通配符? [英] Linq to Entities (EF 4.1): How to do a SQL LIKE with a wildcard in the middle ( '%term%term%')?

查看:365
本文介绍了LINQ到实体(EF 4.1):如何做一个SQL LIKE在中​​间(“%长期%长期%')通配符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要搜索这样的:

Post Cereal

和得到这样的:

Post Honey Nut Cereal

其中,外卡将是空格。

我知道我可以做一个SPLIT等一系列与运算,并载有()和翻译到LINQ表达式为每个术语作为规范对象,而不是有没有办法兑现通配符发送到SQL术语?我看着SQL函数它是在LINQ to SQL,但我不知道它是什么在LINQ到实体

I know I could do a SPLIT and a series of ANDs and Contains() and translation to a Linq Expression for each term as a specification object, but isn't there a way to honor wildcards in the term sent to SQL? I looked at SQL functions where it's in Linq to SQL, but I am not sure what it is in Linq to Entities.

我愿做这样的事情:

term = '%' + term.Replace(' ', '%') + '%';
db.table.where( p => System.Data.Objects.SqlClient.SqlFunctions
                     .SqlMethods.Like(p.fieldname, term) );

有什么建议?

推荐答案

我相信你可以使用 SqlFunctions。 PATINDEX

dt.Table.Where(p => SqlFunctions.PatIndex(term, p.fieldname) > 0);

SqlFunctions.PatIndex表现一样的 SQL LIKE 运营商。它支持所有标准通配符包括:

SqlFunctions.PatIndex behaves the same as the SQL LIKE operator. It supports all standard wildcard characters including:


  • 的零个或多个字符的任意字符串

  • _ (下划线)任何单个字符。

  • [] 在指定范围内的任何单个字符( [AF])或集合([abcdef])中。

  • [^] 的任何单个字符不在指定范围([^ AF])或集合( [^ abcdef])中。

  • % Any string of zero or more characters.
  • _ (underscore) Any single character.
  • [ ] Any single character within the specified range ([a-f]) or set ([abcdef]).
  • [^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

SqlFunctions.PatIndex往往可当SqlMethods.Like不可用(包括MVC控制器内)

SqlFunctions.PatIndex is often available when the SqlMethods.Like is not available (including within MVC controllers)

这篇关于LINQ到实体(EF 4.1):如何做一个SQL LIKE在中​​间(“%长期%长期%')通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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