The_Cthulhu_Kid
The_Cthulhu_Kid

Reputation: 1859

Using a List in a where clause in Entity Framework

I am trying to retrieve document id's over a one-to-many table. I want to use a List in the where clause to find all id's that are connected with every element in the list.

List<int> docIds = (from d in doc
                      where _tags.Contains(d.Tags)
                      select d.id).ToList<int>();

I know that the contains must be incorrect but I can't work it out. If I try a foreach I can't work out how to check if the document contains all Tags.

Upvotes: 3

Views: 7438

Answers (2)

Yv&#225;n Ecarri
Yv&#225;n Ecarri

Reputation: 1738

Use a join:

List<int> docIds = (from d in doc
from t in tags
where d.Tags.Contains(t)
select d.id).ToList<int>();

Upvotes: 0

nemesv
nemesv

Reputation: 139778

If you want that all d.Tags should be in the included in the _tags list, you can try:

List<int> docIds = (from d in doc
                      where d.Tags.All(t => _tags.Contains(t))
                      select d.id).ToList<int>();

If you want that d.Tags should contain all the item from _tags you need:

List<int> docIds = (from d in doc
                      where _tags.All(t => d.Tags.Contains(t))
                      select d.id).ToList<int>();

But I don't know how it translates to SQL by EF so maybe you need to evaluate it on the client site.

Upvotes: 2

Related Questions