how to get sub data in entityframework core?

mc 5,186 Reputation points
2023-02-21T07:25:03.7033333+00:00

I have table:

Id ParentId
1
2 1
3 1
4 2
5 2
6 3
7 10
8 11
9
10
11

public class Comp{ [Key] public string Id{get;set;} public string TopId{get;set;} }

I want to get all Ids that related to the one Id.

If Id=1 I want to get 2,3,4,5,6

If Id= 2 I want to get 4,5

If Id=6 I want to get 6

how to do this in ef core?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
779 questions
{count} votes

1 answer

Sort by: Most helpful
  1. PatriceSc 171 Reputation points
    2023-02-21T10:28:58.17+00:00

    Hi,

    In short you want to get a single flat list with a node id as well as all its direct and indirect childs id?

    Basically you'll need a recursive method that loads chidls from an id (or from a list of ids). You'll call that for the root id and each time it load childs it will call itself recursively to load childs for those childs etc... until no more childs are loaded.

    Another option is to use a server side "recursive common table expression" if using SQL Server.

    Edit: I created a sample at https://dotnetfiddle.net/2tULlj so that you can get the idea.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.