Search code examples
c#entity-frameworkasp.net-coreentity-framework-6

Entity Framework search multiple words


I want to create a search query with Entity Framework (EF6) . To better understand I will explain with example.

I have 5 words(string).

  1. "My name is jack"

  2. "My age is 35 years old"

  3. "My job is developper"

  4. "what is your name"

  5. "China's population is over 1 billion"

Now i want to create an EF query search that having the following results:

  • When search is My name the results are numbers 1 and 2 and 3 and 4
  • When search is is the results are numbers 1 and 2 and 3 and 4 and 5

This is my query:

var query = (from q1 in _db.QuestionTbl where q1.questionTitle.Any(a => q1.questionTitle.Contains("search")) select q1).ToList();

But i can`t get correct answer.


Solution

  • @jonaChaz's answer works, but is inefficient in one important way: it will produce 1 round-trip query to SQL for each term in the search. If you write it this way instead, EntityFramework compiles it into a single query / round trip to the server and can save significant overhead, especially for multi-term searches:

        string search = "My name";
        var terms = search.Split(' ');
        var results = _db.QuestionTb1
            .Where(q => terms.Any(term => q.questionTitle.Contains(term)))
            .ToList();