Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework search records with a list of strings?

I have a database of records that each have a title. I want to be able to search through this database with a search string that will be separated into a list or an array.

So for example if I search with "Book Dog", it will search for all titles that have "Book" or "Dog" in the title.

I'm using entity framework and I guess the simplest way to write down what I want to do is

string[] words;
var posts = (from p in ctx.posts
where p.title.contains(words)
select p).ToList();

I've tried using a StringExtension I found online, but I would get the following error "LINQ to Entities does not recognize the method 'Boolean ContainsAny(System.String, System.String[])' method, and this method cannot be translated into a store expression."

And the extension is

public static bool ContainsAny(this string str, params string[] values)
    {
        if (!string.IsNullOrEmpty(str) || values.Length > 0)
        {
            foreach (string value in values)
            {
                if (str.Contains(value))
                    return true;
            }
        }

        return false;
    }
like image 487
SikhWarrior Avatar asked Dec 17 '25 19:12

SikhWarrior


2 Answers

Are you looking for this?

var posts = (from p in ctx.posts
    where words.Any(w => p.title.Contains(w))
    select p).ToList();
like image 159
Win Avatar answered Dec 20 '25 11:12

Win


Is this what you need:

ctx.posts.Where(post => words.Any(word => post.Title.Contains(word)))
like image 43
Mariusz.W Avatar answered Dec 20 '25 12:12

Mariusz.W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!