Yulian
Yulian

Reputation: 6769

How can I check whether an item of an Entity's child collection exists in another collection with LINQ to Entities?

I hope that somebody caught the idea from the question, but I didn't know how to summarize it better.

The thing is I try to make a simple search in an application. I have Question and Tag entities, like these in StackOverflow - in a many-to-many relationship.

I pass an array of tag IDs to my filtering method. It should return all the Question entities that have this tags (with this IDs). I did it like this:

int[] tagIds = { 1, 2, 3};
var questions = myEntities.Questions
                    .ToList()
                    .Where(q => tagIds.Intersect(q.Tags.Select(t => t.Id).ToArray()).Any())
                    .ToList();

Everything worked fine, but now I added more filters and more methods use this filter, so I want to get a DbQuery object, instead of a List.

I tried removing the .ToList() expressions, to get the appropriate result:

int[] tagIds = { 1, 2, 3};
var questions = myEntities.Questions
                    .Where(q => tagIds.Intersect(q.Tags.Select(t => t.Id).ToArray()).Any());

Unfortunatelly, I get an exception, stating that LINQ does not recognize the .ToArray() method. Can anyone give me a better idea how to achieve this?

Upvotes: 1

Views: 260

Answers (1)

T_D
T_D

Reputation: 1728

The ToArray() method isnt even needed in

.Where(q => tagIds.Intersect(q.Tags.Select(t => t.Id).ToArray())

because Intersect just needs an IEnumerable that Select already returns and not necessarily an array.

Upvotes: 1

Related Questions