Entity Framework 6 - Handling loading of nested objects

荒凉一梦 提交于 2019-12-10 23:44:43

问题


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:


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.



来源:https://stackoverflow.com/questions/24588568/entity-framework-6-handling-loading-of-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!