Entity Framework search records with a list of strings?

asp.net asp.net-mvc-4 entity-framework sql

Question

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;
    }
1
2
4/26/2013 10:12:15 PM

Accepted Answer

Are you looking for this?

var posts = (from p in ctx.posts
    where words.Any(w => p.title.Contains(w))
    select p).ToList();
10
4/26/2013 10:28:08 PM

Popular Answer

Is this what you need:

ctx.posts.Where(post => words.Any(word => post.Title.Contains(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