Possible Duplicate:
How to do SQL Like % in Linq?
Im using mvc 3 and entity framework. How do i do a like search with linq or a lambda expression. Please assisst
Since the goal is for EF expressions to be parsed into SQL, where the LIKE
predicate should be applied, there are at least 3 ways to do this, depending on where you want the %
wildcard to be placed
C#:
.Where(customer => customer.Name.StartsWith("Bloggs"))
=> SQL
WHERE c.Name LIKE 'Bloggs%'
C#:
.Where(customer => customer.Name.Contains("Bloggs"))
=> SQL
WHERE c.Name LIKE '%Bloggs%'
C#:
.Where(customer => customer.Name.EndsWith("Bloggs"))
=> SQL
WHERE c.Name LIKE '%Bloggs'
When applicable, for performance reasons, StartsWith
should be preferred over the other two, given that it has a better chance of using an index on the column.
LIKE %x%
or LIKE %x
will generally result in an index or table scan, unless an unusual index is created on the column.