我想创建递归类别。使用连接时不加载任何项目。我不想外连接,因为如果一个类别没有项目,就不要显示。我该如何解决这个问题?
public string CategoryTree(int depth)
{
StringBuilder sBuilder;
using (DataContext db = new DataContext())
{
var query = from n in db.Categories join m in db.Products on n.CatId equals m.CategoryId where n.ParentId == depth select new{n, m};
sBuilder = new StringBuilder("<ul>");
foreach (var q in query)
{
sBuilder.Append("<li>");
sBuilder.Append("<a href='/Product/"+q.m.ProdId+">'"+q.n.Title+"</a>"+CategoryTree(q.n.CatId));
sBuilder.Append("</li>");
}
sBuilder.Append("</ul>");
}
return sBuilder.ToString();
}
Categories
+---------+---------------+------------+
| CatId | Title | ParentId |
+---------+---------------+------------+
| 1 | Electronic | NULL |
+---------+---------------+------------+
| 2 | Computer | NULL |
+---------+---------------+------------+
| 3 | Television | 1 |
+---------+---------------+------------+
| 4 | Led | 3 |
+---------+---------------+------------+
| 5 | Printer | 2 |
+---------+---------------+------------+
| 6 | Laser Printer | 5 |
+---------+---------------+------------+
Products
+---------+---------------+------------+
| ProdId | ProductName | CategoryId |
+---------+---------------+------------+
| 1 | Samsung LED | 4 |
+---------+---------------+------------+
| 2 | Sony LED TV | 4 |
+---------+---------------+------------+