EF Core:急切加载(.include)子类别(自我参考) [英] EF Core: Eager loading (.Include) sub-categories (self-reference)

查看:60
本文介绍了EF Core:急切加载(.include)子类别(自我参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有这样的东西

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

该方法可以处理并处理多达4级深度的子​​类别(这已经足够了,但现在谁知道未来)

That works and handles sub-categories up to 4-level deep (which is enough for now but who knows the future)

有更好的方法吗?

更多信息

More info

我们首先使用数据库.类别表包含以下列:

We use database-first. Category table has these columns:

  • 编号
  • ParentCategoryId<-这具有Category.Id的外键

推荐答案

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

Firstly, add data annotations and make properties readable

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
}

然后,假设我们有一个类别

then, let's say we have got a category,

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

然后我们得到它的父母:

then we get its parents with:

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

通过以下扩展,我们可以轻松获得其级别:

by following extension, we can easily get its level:

///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;
    }
}

这篇关于EF Core:急切加载(.include)子类别(自我参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆