2

Here is a simplified version of a class hierarchy I am using with entity framework.

public class Questionnaire
{
   public int Id { get; set; }
   public ICollection<Question> Questions { get; set; }
}

public class Question
{
   public int Id { get; set; }
   public ICollection<Question> ChildQuestions { get; set; }

   // Navigation properties
   public int QuestionnaireId { get; set; }
   public virtual Questionnaire Questionnaire { get; set; }
   public int? ParentQuestionId { get; set; }
   public virtual Question ParentQuestion { get; set; }
}

So a questionnaire has a collection of questions and each question can have its own collection of child questions.

The problem I face is that when I retrieve a questionnaire from the database the collection of questions it holds includes all questions associated with that questionnaire, including ones which are nested within other questions.

The questions themselves correctly contain references to their child questions.

At the moment I'm working around it by removing all Questions from the Questionnaire.Questions collection where ParentQuestionId != null.

Is there a way of telling Entity Framework to only include in Questionnaire.Questions the Questions which have a null ParentQuestionId?

1 Answer 1

3

In your controller :

Questionnaire questionnaire = 
    db.QuestionnaireDBSet
      .Include(x => x.Questions.Where(q => q.ParentQuestionId == null))
      .FirstOrDefault(x => x.Id == id);

Assuming db is your QuestionnaireDBContext...

EDIT : As the OP said, it seems we can't filter using Include. So the answer above would only work in a perfect world. But now you should try something like this instead :

Questionnaire questionnaire = 
    db.QuestionnaireDBSet
      .Include(x => x.Questions)
      .Where(x => x.Questions.Any(q => q.ParentQuestionId == null))
      .FirstOrDefault(x => x.Id == id);

I don't have any test environment so i can only give you some suggestions.

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

3 Comments

or should that be != null ?
@philsoady "which have a null ParentQuestionId" sayd the OP
Thanks, but this doesn't work for me. I get the error: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Also, I've read that Include does not support filtering, or has it been added in the latest EF version?

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.