0

I am new to the entity framework and trying to get data using foreign key from Answers table but I am getting error

The nested query is not supported. Operation1='Case' Operation2='Collect'

p.Answers.Count() or p.Answers.SingleOrDefault().correct_answeras string works fine but p.Answers.Select(c => c.correct_answer).ToList() throwing nested query error

I want to keep it in one query because there could be thousands of questions so I don't want to check answers to the separate queries. Following is my code.

return db.Questions.Where(p => p.q_id == q_id).Select(p => new QuestionViewModel
{
   q_id = p.q_id,
   q_text = p.q_text,
   q_answer = p.Answers.Count() > 0 ? p.Answers.Select(c => c.correct_answer).ToList() : null
}).OrderBy(x => x.q_id).ToList();

ViewModel

public class QuestionViewModel
{
    public long q_id { get; set; }
    public string q_text { get; set; }
    public List<string> q_answer { get; set; }
}

1 Answer 1

2

The exception is telling you that EF does not support conditional subquery, implied by expressions like this:

p.Answers.Count() > 0 ? p.Answers.Select(c => c.correct_answer).ToList() : null

So simply remove the conditional operator:

q_answer = p.Answers.Select(c => c.correct_answer).ToList()

In case there are no related answers for question, q_answer will be populated with empty list rather than null, which is the normal (expected) behavior for collection type objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't know EF doesn't support conditional subquery. Without conditional subquery, it's working fine. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.