首页 > 解决方案 > EF Core:急切加载 (.Include) 子类别(自引用)

问题描述

我们有这样的东西

var categories = _context.Categories.Include("Categories1.Categories1.Categories1");

这可以工作并处理高达 4 级深度的子​​类别(现在就足够了,但谁知道未来)

有更好的方法吗?

更多信息

我们使用数据库优先。类别表具有以下列:

标签: entity-frameworkentity-framework-core

解决方案


首先,添加数据注释并使属性可读

public partial class Category
{

    public Category()
    {
        this.Children = new HashSet<Category>();
    }

    [Key]
    public int Id { get; set; }

    public string WhatEverProperties { get; set; }

    public int ParentCategoryId { get; set; }


    [ForeignKey("ParentCategoryId")]
    [InverseProperty("Category")]
    public Category Parent { get; set; } // name "Category1" as "Parent"

    [InverseProperty("Category")]
    public ICollection<Category> Children { get; set; } // Name it as Children
}

那么,假设我们有一个类别,

var category = context.Categories
    .Include(x => x.Parent)
    .Include(x => x.Children)
    .FirstOrDefault(filter);

然后我们得到它的父母:

var rootCategory = category.Parent?.Parent?.Parent; //up-to 4 levels by your request

通过以下扩展,我们可以很容易地得到它的等级:

///this extension works only if you used `.Include(x => x.Parent)` from query
public static class CategoryExtensions
{
    public static int Level(this Category category)
    {
        if (category.Parent == null)
        {
            return 0;
        }

        return category.Parent.Level() + 1;
    }
}

推荐阅读