Entity Framework search multiple words

asp.net-core c# entity-framework entity-framework-6

Question

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.

1
1
7/8/2019 7:32:38 PM

Accepted Answer

@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();
5
7/8/2019 8:10:46 PM

Popular Answer

    string search = "My is";
    var arr = search.Split(' ');

    List<QuestionTb1> query = new List<QuestionTb1>();
    foreach (var word in arr)
    {
        var newQuestionTb1s = _db.QuestionTb1.Where(a => a.questionTitle.Contains(word)).Except(query).ToList();
        query.AddRange(newQuestionTb1s);
    }

this code splits the search text by 'Words'(spaces) and then get the questions with the searchtext word by word.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow