2
votes

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

1 Answers

3
votes

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.