本文介绍了实体框架6 - 嵌套对象的处理负荷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我与实体框架使用类层次结构的简化版本。

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.

在目前我的工作围绕它通过删除所有问题 Questionnaire.Questions 集合,其中 ParentQuestionId!= NULL

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

有没有告诉实体框架的方式,只包含 Questionnaire.Questions 问题其中有一个空 ParentQuestionId

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

推荐答案

在你的控制器:

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



假设分贝是QuestionnaireDBContext ...

Assuming db is your QuestionnaireDBContext...

编辑:作为OP说,看来我们无法过滤用include。所以,上面的答案只会在一个完美的世界而努力。但是,现在你应该尝试这样的事情,而不是:

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.

这篇关于实体框架6 - 嵌套对象的处理负荷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 22:23