Wendy Wendy - 1 year ago 119
MySQL Question

How to find all child elements in Entity Framework

I have a root table that display data as below

Test1
-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 -

rootTable
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;

            childItems.Add(child);

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

Uses

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