wardh
wardh

Reputation: 479

Having trouble nesting Lambda with LINQ in EF4

I'm getting the following exception when trying to perform the following LINQ-query nested with Lambda.

Unable to create a constant value of type . Only primitive types ('such as Int32, String, and Guid') are supported in this context.

If I remove the lambda it works fine, but then I don't get the result I want of course.

var context = new dbContext();
            var searchQuery = (from q in context.Questions
                               where q.Topic.Contains(searchTerm) || q.QuestionText.Contains(searchTerm)
                               select q).ToList();
            var questionsBasedOnTags = (from tags in context.Tags
                                        where tags.Tag.Contains(searchTerm)
                                        select tags).ToList();
            List<QuestionHasTags> tagQuestionIds = new List<QuestionHasTags>();
            foreach (var item in questionsBasedOnTags)
            {
                var getQuestionIds = (from q in context.QuestionHasTags
                                      where context.QuestionHasTags.Any(o => o.TagId == item.TagId && !searchQuery.Any( w => w.QuestionId == o.Questions.QuestionId) && !tagQuestionIds.Any(z => z.QuestionId == o.Questions.QuestionId))
                                      select q).ToList();
                foreach (var questionHasTagId in getQuestionIds)
                {
                    tagQuestionIds.Add(questionHasTagId);
                }
            }

Any clues on why I'm getting the exception, what I've done wrong or another way to do it?

Thanks in advance for the help.

Upvotes: 1

Views: 153

Answers (1)

Scott Weinstein
Scott Weinstein

Reputation: 19117

searchQuery is not a Query, but a list, b/c you forced execution via ToList()

Mixing a list with context.QuestionHasTags isn't working. One approach to fix this would be to merge the upper and lower queries into one.

Upvotes: 2

Related Questions