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


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


If you've configured the PK-FK correctly in the DB, LINQ to SQL will do the object association for you. Thus, the EntitySet property ProductSubCategory will appear in ProductCategory.



The key is that you DB PK-FK ref must be correct for a LINQ code generator to select this.

0


a source







All Articles