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

后端 未结 3 1545
陌清茗
陌清茗 2021-01-01 16:04

I want to search for this:

Post Cereal

and get this:

Post Honey Nut Cereal

where the wild cards would be

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 16:27

    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)

提交回复
热议问题