层次模型绑定

时间:2018-10-17 14:23:32

标签: c# entity-framework linq

我已经编写了用于获取位置的分层数据的代码。我只能将层次结构提高到两个级别,但是我正在寻找第n个层次结构。我还编写了递归函数,但是无法将数据添加到层次结构中。

数据模型类:-

public class RoomDTO
    {
        public Guid RoomId { get; set; }
        public string Name { get; set; }    

        public Guid? ParentRoomId { get; set; }       
        public List<RoomDTO> Children { get; set; } = new List<RoomDTO>();

    }

父级功能:-

private List<RoomDTO> RoomData(List<SubLocation> subLocations)
        {
            List<RoomDTO> rooms = new List<RoomDTO>();
            foreach (var location in subLocations.Where(x => x.HasChildLocations))
            {
                var subLocationDTO = new RoomDTO
                {
                     RoomId = location.SubLocationId
                     ,Children = getChild(subLocations, location, new RoomDTO()).Children
                };

                rooms.Add(subLocationDTO);
            }
            return rooms;
        }

递归函数:-

private RoomDTO getChild(List<SubLocation> list, SubLocation location, RoomDTO roomDTO)
        {

            var child = list.Where(x => x.ParentSubLocationId == location.SubLocationId).ToList();
            for (int i = 0; i < child.Count; i++)
            {
                var childRoom = new RoomDTO {
                    ParentRoomId = child[i].ParentSubLocationId
                    , RoomId = child[i].SubLocationId
                };                
                roomDTO.Children.Add(childRoom);
                getChild(list, child[i], roomDTO);
            }
            return locList; 
        }

呼叫功能:-

 public void GetRoomList()
{
            var subLocationList = _context.SubLocations.AsNoTracking().ToList();

            var data = RoomData(subLocationList);

}

请告诉我我在这里做什么不正确。

1 个答案:

答案 0 :(得分:0)

我按照以下步骤解决了该问题, 1>在表中添加了Field(SortId)以标识父项和子项的顺序。 2>从项目列表中,根据ParentId过滤数据,然后按SortId排序

if (summaryList.Count > 0)
            {
                //make Mneu structure 
                foreach (var menu in summaryList.Where(x => x.data.ParentSubLocationId == null).OrderBy(x => x.data.SortId))
                {
                    menu.children = GetChildMenuIetms(menu, summaryList);
                    menus.Add(menu);
                }
            }

3>在上面的foreach循环中,执行了递归的GetChildMenuItem函数以获取子项,如下所示,

public List<Child> GetChildMenuIetms(Child menuItem, List<Child> menuItems)
    {
        List<Child> childerns = null;
        childerns = menuItems.Where(x => x.data.ParentSubLocationId == menuItem.data.SubLocationId).OrderBy(x => x.data.SortId).ToList();

        if (childerns != null && childerns.Count > 0)
        {
            for (int i = 0; i < childerns.Count; i++)
            {

                childerns[i].children = GetChildMenuIetms(childerns[i], menuItems.Where(x => !childerns.Any(c => c.data.SubLocationId == x.data.SubLocationId)).ToList());
            }
        }
        return childerns;
    }