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
?