How to query a database table that references itself via an intermediate table and extract all the data

Viewed 31

I have two tables, the main item table and the intermediate itemXitem table, which are used to generate a BOM list.

Item

| Id | Name      |ItemType_id(FK)|
| -- | --------- |---------------|
| 1  | Raw Item 1| 3             |
| 2  | Assy Item1| 2             |
| 3  | Raw Item 2| 3             |
| 4  | Top 1     | 1             |

ItemXItem

| Id | Parent_Id(FK) | Child_Id(FK) |
| -- | ------------- |------------- |
| 1  | 2             | 1            |
| 2  | 4             | 2            |
| 3  | 4             | 3            |

ItemType_id (1: Top, 2: Assembly, 3: Raw Material)

I extract the information from C# through a recursive method that converts it into a IQueryable.

This is the code

  public IQueryable<Item> GetChildsByParentId(long Id){
        List<ItemXItem> itemsXItems = new List<ItemXItem>();
        List<Item> items = new List<Item>();
        items.Add(db.Items
            .AsNoTracking()
            .Include("ItemType")
            .Include("ItemXItems")
            .Include("ItemXItems1")
            .Where(x => x.Id == Id).FirstOrDefault());

        GetAllChilds(Id, itemsXItems);
        foreach (ItemXItem element in itemsXItems)
        {
            items.Add(db.Items
            .AsNoTracking()
            .Include("ItemType")
            .Include("ItemXItems")
            .Include("ItemXItems1")
            .Where(x => x.Id == element.Child_Id).FirstOrDefault());
        }
        return items.AsQueryable();
    }

    private List<ItemXItem> GetAllChilds(long id, List<ItemXItem> itemsXItems)
    {
        List<ItemXItem> itemData = db.ItemXItems.Where(x => x.Parent_Id == id).ToList();
        foreach (ItemXItem element in itemData)
        {
            int items = db.ItemXItems.Where(x => x.Parent_Id == element.Child_Id).Count();
            if (items > 0)
            {
                itemsXItems.Add(element);
                GetAllChilds(element.ChildId, itemsXItems);
            }
            else
            {
                itemsXItems.Add(element);
            }
        }
        return itemsXItems;
    }

The problem is performance, the response time is affected by being a recursive function and by the number of levels it can go down to the final element (raw material).

I was looking for options to make the database server through a query allow me to extract the information, without having to use that recursion function. Any ideas. Thanks

0 Answers
Related