简体   繁体   中英

Perform string search with Linq to Entities

I want to enable this function in Linq to Entities (so the filtering happens on the SQL Server)?

public static bool ContainsAny(this string source, StringComparison comparison,
                               IEnumerable<string> searchTerms)
{
  return searchTerms.Any(searchTerm => source.Contains(searchTerm, comparison));
}

My goal is search a table and limit the result by filtering a certain column with the above function, ie GetContacts().Where(c => c.FullName.ContainAny(searchTerm)) .

First, it's tricky (if possible which I don't know) to use StringComprison in Expressions and expect Linq 2 Entities to translate it to correct Sql statements.

Second, it's tricky to use a custom function like your ContainsAny in an Expression too.

So if I were you, the simple solution is:

GetContacts().Where(c => searchTerms.Any(term => c.FullName.Contains(term)))

which should work in EF4.

Take a look at a nuget package I have created

http://www.nuget.org/packages/NinjaNye.SearchExtensions

This will enable the following (and more) which will return results where the search term appears in property specified

var result = GetContacts().Search("searchTerm", c => c.FullName);

For searching multiple terms you can do the following:

var result = GetContacts().Search(searchTerms, c => c.FullName);

The above will return results where any search term appears in the property

This builds up an expression tree which performs the search on the database not in memory, so only matching results are returned form the server.

For more information take a look at the projects GitHub page or my blog posts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM