5

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

?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
JJ.
  • 9,580
  • 37
  • 116
  • 189

2 Answers2

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

   Contains() is translated LIKE '%term%'
   StartsWith() = LIKE 'term%'
   EndsWith()   = LIKE '%term'
Nick
  • 4,192
  • 1
  • 19
  • 30
5

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • any idea if i can make my own expression? i would pass a string – CMS Aug 09 '16 at 09:01
  • im not sure why but if i call do it in EF6 i get an error converting store expression Boolean like(System.String,System.String) – CMS Aug 09 '16 at 18:50
  • 1
    I guess EF uses Linq-to-Entity, while this `SqlMethods` only work with Linq-to-SQL. `StartsWith` works for me. – Hp93 May 12 '20 at 07:26