asp.net mvc c# 递归列出类别

asp.net mvc c# listing categories recursively

我正在尝试用我的类别数据填充一个列表。 我的类别具有级联格式。它们在我的数据库中递归格式化。 这是我的模型对象。

public class CategoriesDTO
{
    public int Id { get; set; }
    public int Level { get; set; }
    public string Name { get; set; }
    public List<CategoriesDTO> Subs { get; set; }
}

因此,在我的业务层中,我尝试这样调用此方法:

DAO.Categories(0);

它将以"Level==0"条件开始,然后继续.. 但我无法管理数据访问层。我试过这个:

public List<CategoriesDTO> Categories(int PrmLevel)
{
    List<CategoriesDTO> DTO = new List<CategoriesDTO>();
    //DB is my dbcontext.
    DTO = DB.Categories.Select(x => new CategoriesDTO()
    {
        Id = x.Id,
        Level = x.Level,
        Name = x.Name
        }).Where(y => y.Level == PrmLevel).ToList();
        foreach (var item in DTO)
        {
            //im stucked
        }
        return DTO;
    }
}
public List<CategoriesDTO> Categories(int PrmLevel)
{
    List<CategoriesDTO> DTO = new List<CategoriesDTO>();
    //DB is my dbcontext.
    DTO = DB.Categories.Select(x => new CategoriesDTO()
    {
        Id = x.Id,
        Level = x.Level,
        Name = x.Name
        }).Where(y => y.Level == PrmLevel).ToList();
        foreach (var item in DTO)
        {
            item.Subs = ((PrmLevel + 1) <= MaxLevel) ? Categories(PrmLevel + 1) : null;
        }
        return DTO;
    }
}
public List<CategoriesDTO> Categories(int PrmLevel)
{
    List<CategoriesDTO> DTO = new List<CategoriesDTO>();
    //DB is my dbcontext.
    DTO = DB.Categories.Select(x => new CategoriesDTO()
    {
        Id = x.Id,
        Level = x.Level,
        Name = x.Name
        }).Where(y => y.Level == PrmLevel).ToList();
        foreach (var item in DTO)
        {
            int CountSub = 0;
            CountSub = DB.Categories.Where(x => x.Level == item.Id).ToList().Count();
            if (CountSub!=0)
            {
                item.Subs = Categories(item.Id).ToList();
            }
        }
        return DTO;
    }
}