Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How to create a self referencing tree #857


User avatar
0
princedis created

I have to create a self referencing tree like category, subcategory entity which is similar to OrganizationUnit.

public class Category
{

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

    [StringLength(40)]
    public string Name { get; set; }

    public int? ParentId { get; set; }

    [JsonIgnore]
    public virtual ICollection<Category> Children { get; set; }

    [JsonIgnore]
    public virtual Category Parent { get; set; }
}

3 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Your entity seems fine except it must be derived from Entity class and should not include Id (since Entity defines it).

  • User Avatar
    0
    alaamh created

    I have a question regarding application service implementation of GetCategories:

    var categories = await _categoryRepository
                    .GetAll()
                    .Include(c => c.Children)
                    .WhereIf(!input.Filter.IsNullOrEmpty(),
                        c => c.DisplayName.Contains(input.Filter)
                    )
                    .ToListAsync();
    

    it's dump all the database, how to avoid that? I want to load only parent category with childrens of this parent

    Thank you.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    I think, it is really hard to write query of what you are asking with LinQ. Instead of this, get all list of categories and process them to create a tree in your app service.