0

I have a field "details" varchar(MAX) in my table with the detailed description of an item, I need to select the records that contain the keywords passed by the user in a string array.

var searchTerms = new List<string> { "car", "black", "bike", "blue" };

I tried to do it like this:

var result = (from i in _contexto.itens
where searchTerms.Any(d => i.details.Contains(d))
select i.id);

and I get the following error:

The LINQ expression 'DbSet() .Where(i => __searchTerms_0 .Any(d => i.details.Contains(d)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I also tried this link's approach using the "SearchExtensions nuget package" and the same error occurs.

How can I do this? or should I make a query for each item in the array?

Example of a text I want to search for:

It is a long established fact that a car will be distracted by the readable content of a page when looking at its bike. The point of using Lorem Ipsum is that it has a more-or-less normal distribution

Thanks!

stuartd
  • 70,509
  • 14
  • 132
  • 163
Dark Ducke
  • 145
  • 1
  • 3
  • 12
  • That link is of course a rip-off of a SO question - https://stackoverflow.com/questions/27295702/how-do-you-check-if-a-string-contains-any-strings-from-a-list-in-entity-framewor – stuartd May 07 '22 at 00:50
  • hello, I had already seen this link and tried his approaches, but the same error mentioned in my question occurs. – Dark Ducke May 07 '22 at 01:26
  • *I also tried ... using the "SearchExtensions nuget package"* - make yourself easy to help: show what you tried; we cannot debug code that we cannot see – Caius Jard May 07 '22 at 07:09

2 Answers2

0
var searchTerms = new List<string> { "car", "black", "bike", "blue" };
        
        string examplestring = "It is a long established fact that a car will be distracted by the readable content of a page when looking at its bike. The point of using Lorem Ipsum is that it has a more-or-less normal distribution";

        var result = searchTerms.Select(s => (examplestring.Contains(s)) ? (object)searchTerms.IndexOf(s) : null).Where(w => w != null).ToList();
0

Adapting Alexander's advice from the link you gave, for your situation:

var searchTerms = new List<string> { "car", "black", "bike", "blue" };

Expressions<Func<TYPE_OF_OBJECT_IN_ITENS_HERE, bool>> expression = it => false;
foreach(var searchTerm in searchTerms)
{
    expression = expression.Or(it => it.details.Contains(searchTerm));
}
var result = _contexto.itens.Where(expression);

You didn't post any detail about the type of object inside itens, so you'll have to replace that above

Caius Jard
  • 72,509
  • 5
  • 49
  • 80