How do I get wildcard text searches (like SQL's "like" statement) in ASP.net MVC using the edo entity framework?
I assumed this would work:
var elig = (from e in _documentDataModel.Protocol_Eligibility_View
where e.criteria.Contains(query)
select e);
But it returns no results even when searching for a query string that's definitely in the database. What am I doing wrong?
I started using the code that Jon Koeter posted from the blog post in another answer that no longer appears to exist.
However, I found it didn't really work properly, especially when using an
IEnumerable
. Namely, it was resolving the enumerable usingToArray
and using a regex to match, rather than the built in functions.Since I only want to resolve my
IEnumerable
once I have finished filtering, I made some changes to convert to anIQueryable
then use the rest of the code to find the correct Entity Framework method and call that. This way, the query itself is not called against the database until later, and it avoids the use of a regex.Usage:
Linq to entities does not support the SqlMethods method, but you could use the string functions instead:
String.Contains should work appropriately. SQL's LIKE statement is typically handled via String.StartsWith, String.Contains, or String.EndsWith.
However, it is possible you're having casing issues. You could try:
This guy made a very nice "WhereLike" extension for Linq that accepts any wildcard character and compares two values (one of which comes from an expression) with a generic method derived from the location of the wildcard.
http://trentacular.com/2010/08/linq-to-entities-wild-card-like-extension-method/
EDIT: The article seems to be down. I will paste the extention code below:
The System.Data.Linq.SqlClient namespace contains the SqlMethods class. You can use it's Like method like this:
2019 update
For Entity Framework 6.2 you can use DBFunctions
For example: