EF Core resursive model - order alphabetically on the same level

Viewed 34

We are using .NET Core 3.1 and Microsoft.EntityFrameworkCore 3.1.9. We have the following recursive database model:

[Table("category", Schema = "test")]
public partial class Category
{
    public Category()
    {
        InverseIdParentNavigation = new HashSet<Category>();
    }

    [Key]
    [Column("id")]
    public int Id { get; set; }
    
    [Column("id_parent")]
    public int? IdParent { get; set; }
    
    [Required]
    [Column("name")]
    [StringLength(128)]
    public string Name { get; set; }

    [ForeignKey(nameof(IdParent))]
    [InverseProperty(nameof(Category.InverseIdParentNavigation))]
    public virtual Category IdParentNavigation { get; set; }

    
    [InverseProperty(nameof(Category.IdParentNavigation))]
    public virtual ICollection<Category> InverseIdParentNavigation { get; set; }
}

How can we order categories alphabetically by Name at the same level (inside InverseIdParentNavigation)? Example of result:

Root_1
    j
    k
    l
Root_2
    a
    b
        a
        b
    c

Categories at the same level are ordered alphabetically:

  1. Level 0: Root_1 < Root_2
  2. Level 1: j < k < l and a < b < c
  3. Level 2: a < b

How can we achieve this?

1 Answers

I haven't tested it, but it might be something like the following

public void RecursiveOrder(IEnumerable<Category> categories)
{
    var children = categories.OrderBy(x => x.Name);          
    children.ForEach(u => RecursiveOrder(u.Child);
}
Related