EF Core: Eager loading (.Include) sub-categories (self-reference)

entity-framework entity-framework-core

Question

We have something like this

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

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

Is there a better way to do it?

More info

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

  • Id
  • ParentCategoryId <-- this has foreign key to Category.Id
1
0
7/19/2018 12:15:34 AM

Popular Answer

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;
    }
}
1
1/20/2020 5:38:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow