Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities using the SQL LIKE operator

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);

?

like image 328
JJ. Avatar asked Jun 13 '13 21:06

JJ.


2 Answers

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

   Contains() is translated LIKE '%term%'
   StartsWith() = LIKE 'term%'
   EndsWith()   = LIKE '%term'
like image 193
Nikola Mitev Avatar answered Oct 09 '22 23:10

Nikola Mitev


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.

like image 20
p.s.w.g Avatar answered Oct 09 '22 21:10

p.s.w.g