LINQ to Entities using the SQL LIKE operator

爱⌒轻易说出口 提交于 2019-12-30 20:17:45

问题


I have this:

query = query.Where(s => s.ShowTypeDescription == showTypeDescription);

several times for different variables in order to build dynamic SQL.

How would I go about transforming the above to say:

query = query.Where(s => s.ShowTypeDescription **LIKE** showTypeDescription);

?


回答1:


If all you want is to find a substring within another string, the best way to do this is with the Contains method:

query = query.Where(s => s.ShowTypeDescription.Contains(showTypeDescription));

Because the String.Contains method translates to:

CHARINDEX(ShowTypeDescription, @showTypeDescription) > 0

Which is roughly equivalent to:

ShowTypeDescription LIKE '%' + @showTypeDescription + '%'

Update: In Linq-to-SQL, you can use the SqlMethods.Like method:

query = query.Where(s => SqlMethods.Like(s.ShowTypeDescription, showTypeDescription));

This will directly translate to the SQL LIKE operator. Note, however, this won't work outside of Linq-to-SQL queries. Trying to call this method in other contexts will throw an exception.




回答2:


query = query.Where(s => s.ShowTypeDescription.Contains(showTypeDescription));

   Contains() is translated LIKE '%term%'
   StartsWith() = LIKE 'term%'
   EndsWith()   = LIKE '%term'


来源:https://stackoverflow.com/questions/17097764/linq-to-entities-using-the-sql-like-operator

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