Asp.net MVC - LINQ and Hieararchical data
I have a database with two tables
ProductCategory
IDCat
Name
Description
ProductSubCategories
IDSub
Name
IDCat
These tables are related to IDCat processing.
How can I do with LINQ to get a list of categories and subcategories grouped by category?
In my PartialView, I would like to create a menu with categories and subcategories, for example:
Category1
SubCategory1
SubCategory2
SubCategory3
Category2
SubCategory1
SubCategory2
SubCategory3
Category3
SubCategory1
0
Gabriele
a source
to share
2 answers
MyDataContext db=new MyDataContext();
IQueryable<ProductCategory> categories= db.Categories;
foreach (Category c in categories){
Console.WriteLine (c.Name);
foreach (ProductSubCategories sub in c.ProductSubCategories){
Console.Writeline (sub.Name);
}
}
Edit to answer the question in view format
<% foreach (Category c in Model){ %>
<%= Html.Encode(c.Name) %> <br />
<% foreach (ProductSubCategories sub in Model.Categories){ %>
<%= Html.Encode(sub.Name) %> <br />
<% } %>
<%} %>
This should work (or be close), but I have a tested syntax. Note that, as others have pointed out, your primary and foriegn keys must be configured correctly for this to work.
0
a source to share