Reputation: 8337
I have a an entity let's say call it Blog
. Each Blog
entity has many Keyword
. The 2 are related via an fk on the keyword table.
I have a query with a signature like this FindAllBlogByKeywords(IEnumerable<string> keywords)
How would I write a linq query to pull any blog that matches ALL of the keywords in the parameter.
The problem is EF is not allowing a join between enumerable and tables. It's not contains either because I want the query to match ALL keywords, not just any one - besides I have 2 keywords list, I need the keyword in the parameter to be a subset of the keywords in the persistence.
Upvotes: 0
Views: 320
Reputation: 564531
You can add .Where clauses for each keyword:
IEnumerable<Blog> FindAllBlogByKeywords(IEnumerable<string> keywords)
{
IQueryable<Blog> query = context.Blogs;
foreach(string key in keywords)
query = query.Where(blog => blog.Keywords.Contains(key));
// Execute query (optional)
return query.ToList();
}
This works because the query execution is deferred until the end. By chaining multiple .Where
clauses, you effectively create an "ALL" statement.
Upvotes: 6