Wendy Wendy - 1 year ago 129
MySQL Question

How to find all child elements in Entity Framework

I have a root table that display data as below

-Test 2
- Test 3
- Test 4
New Test

I need to query this table when I select "Test 2" it should return all children elements.

table Definition -

id, name, parentId

Answer Source

Create a recursive method to lookup for child elements from a table.

private List<RootTable> FindChildElements(IEnumerable<RootTable> rootTables, int id, List<RootTable> childItems = null)
            var child = rootTables.Where(s => s.ParentCategoryId == id).FirstOrDefault();

            if (childItems == null)
                childItems = new List<RootTable>
                    rootTables.FirstOrDefault(s => s.Id == id)

            if (child == null)
                return childItems;


            return FindChildElements(rootTables, child.Id, childItems);


var childItems = FindChildElements(_context.rootTable, 4); //pass table data and the selected id
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download