实体框架核心:为具有可变嵌套级别的对象加载嵌套实体

时间:2017-09-29 14:12:23

标签: c# entity-framework asp.net-core

在我的项目中,我有一个名为Question的实体,它有一个名为QuestionCategories的属性,它是QuestionCategory类型的对象的集合:

public class Question : AuditEntity
{
    public long QuestionId { get; set; }
    public string Text { get; set; }
    public byte Complexity { get; set; }
    public short QuestionTypeId { get; set; }

    public QuestionType QuestionType { get; set; }

    public ICollection<AnswerOption> AnswerOptions { get; set; } = new Collection<AnswerOption>();
    public ICollection<QuestionTag> QuestionTags { get; set; } = new Collection<QuestionTag>();
    public ICollection<QuestionCategory> QuestionCategories { get; set; } = new Collection<QuestionCategory>();

}

QuestionCategory类具有类别Category

的属性类别
public class QuestionCategory : AuditEntity
{
    public long QuestionId { get; set; }

    public long CategoryId { get; set; }

    public Question Question { get; set; }

    public Category Category { get; set; }
}

public class Category : AuditEntity
{
    public long CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public long? ParentCategoryId { get; set; }

    public Category ParentCategory { get; set; }

    public ICollection<Category> ChildCategories { get; set; } = new Collection<Category>();

    public ICollection<QuestionCategory> CategoryQuestions { get; set; } = new Collection<QuestionCategory>();
}

每个类别都有属性ParentCategory,即Category类型的对象。所以这里有一个类别树,其分支长度不同,由用户定义。

目前,如果只有根类别及其子类别,我会以这种方式加载一系列问题:

public class QuestionRepository : BaseRepository<Question>, IQuestionRepository
{
    protected override IQueryable<Question> DbQuery => base.DbQuery
        .Include(q => q.QuestionCategories).ThenInclude(qc => qc.Category).ThenInclude(c => c.ParentCategory);

但是,如果有另一个嵌套级别,即上面提到的子类别有自己的子级,我必须添加另一个.ThenInclude()语句:

public class QuestionRepository : BaseRepository<Question>, IQuestionRepository
{
    protected override IQueryable<Question> DbQuery => base.DbQuery
        .Include(q => q.QuestionCategories).ThenInclude(qc => qc.Category).ThenInclude(c => c.ParentCategory).ThenInclude(c => c.ParentCategory);

等等......

问题是每个问题的嵌套级别数量不同,数量不受限制。因此,我应该以某种方式计算每个问题的类别级别的数量,并为每个级别调用.ThenInclude()。

但是,我不知道如何实现它。任何帮助都非常感谢。

谢谢!

1 个答案:

答案 0 :(得分:0)

您是否真的试图访问所有级别,或者您是否只是假设您必须拥有可变数量的包含才能实现这一目标?

至少在EF的早期版本中,只需要包含一个级别的自引用层次结构。拉入一个自引用关系级别的查询实际上具有连接该关系的所有级别所需的所有数据。由于像EF这样的ORM的工作方式,一旦该数据可用,就可以构建整个对象图而无需显式发出进一步的查询。我不确定它在EF Core中是否仍然可以这样工作,但我认为没有任何理由不应该这样。它起作用的基本原则在两者中保持不变。