0

我想在我的网页上为产品类别制作递归类别菜单。每个类别必须根据“产品”表上的 CategoryId 检索相关的第一项,但如果类别没有任何产品,则该类别应该消失。实际上,我可以做到使用 INNER JOIN 轻松进行非递归类别菜单。我该如何解决这个问题?有什么想法吗?

我可以使用如下方法,但这种方法既是业余的,也可能是空的第一项。

类别表

+--------------+---------------+------------+
|  CategoryId  | CategoryName  | ParentId   |
+--------------+---------------+------------+
|      1       | Cookware      |   NULL     |
+--------------+---------------+------------+
|      2       | Tableware     |   NULL     |
+--------------+---------------+------------+
|      3       | Teapots       |     1      |
+--------------+---------------+------------+
|      4       | Cutleries     |     3      |
+--------------+---------------+------------+
|      5       | 30pcs Cutlery |     2      |
+--------------+---------------+------------+

产品表

+--------------+--------------+--------------------+------------+
|  ProductId   | ProductCode  | ProductName        | CategoryId |
+--------------+--------------+--------------------+------------+
|       1      |   G110090    |   Teapot           |      3     |
+--------------+--------------+--------------------+------------+
|       2      |   D220623    |   Cutlery Set      |      5     |
+--------------+--------------+--------------------+------------+ 

RecursiveCategory 方法

public string RecursiveCategory(IEnumerable<Category> category, int? parent)
{
    string catNode = string.Empty;
    if(category.Any(n=>n.ParentId == parent))
    {
        catNode += "<ul>";
            foreach(Category c in category)
            {
                catNode += "<li>";
                catNode += "<a href='/Detail/" + GetFirstItem(c.CategoryId).ProductId + "'>"+c.CategoryName+"</a>";
                catNode += RecursiveCategory(category, c.ParentId);
                catNode += "</li>";
            }
        catNode += "</ul>"
    }
    return catNode;
}

GetFirstItem 方法

public Product GetFirstItem(int categoryId)
{
    Product prod = new Product();
    foreach(Product p in db.Product.Where(n=>n.CategoryId == categoryId))
    {
        prod.ProductId = p.ProductId;
        prod.ProductName = p.ProductName;
        ...
    }
    return prod;
}
4

1 回答 1

0

试试这个从给定点构建层次结构(在第一次调用中使用 null 将为您提供包含每个类别产品的完整树)。作为修改,如果您需要,您可以使产品延迟加载:

public class Category
{
  IEnumerable<Category> Children {get;set;}
  IEnumerable<Product> Products {get;set;}
}

public IEnumerable<Category> GetCategory(int? parent)
{
  var result = new List<Category>();
  foreach (var cat in categories.Where(p => p.parentId = parent)
  {
     var generatedCategory = new Category();
     generatedCategory.Children = GetCategory(cat.id);
     generatedCategory.Products = products.Where(p => p.CategoryId = cat.CategoryId);
     result.Add(generatedCategory);
  }
  return result;
}

注意:我没有测试代码,只是关于如何轻松构建它的指南。

于 2013-11-06T12:07:24.133 回答