Linq to Entities (EF 4.1): How to do a SQL LIKE with a wildcard in the middle ( '%term%term%')?

徘徊边缘 提交于 2019-11-30 11:09:42
Jeff Ogata

I believe you could use SqlFunctions.PatIndex:

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

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

  • % 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 is often available when the SqlMethods.Like is not available (including within MVC controllers)

It is probably easier to bypass LINQ and use an Entity SQL filter:

var query - db.table.Where("TRIM(fieldname) LIKE @pattern");
query.Parameters.Add(new ObjectParameter("pattern", term)); // term == "%what%ever%"

and the type of query implements IQueryable<TEntity> so you can apply further LINQ operators.

Just to clarify Ladislav's comment regarding it.BusinessName. I think what he is referring to is prefixing the field name with .it. The above solution works as long as you prefix the field name in the where clause with it.. Also I didn't need the TRIM() in my case.

var query - db.table.Where("it.fieldname LIKE @pattern");
query.Parameters.Add(new ObjectParameter("pattern", term)); // term == "%what%ever%"

It worked perfectly against an Oracle database.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!