I have a database with this two tables
我有一个包含这两个表的数据库
ProductCategory
IDCat
Name
Description
ProductSubCategories
IDSub
Name
IDCat
This tables are related trought IDCat.
这些表与IDCat有关。
How can i do with LINQ to retrieve the list of Category and SubCategory grouped by Category ??
如何使用LINQ检索按类别分组的Category和SubCategory列表?
In my PartialView I would like create a menu with Category and SubCategories like this :
在我的PartialView中,我想创建一个包含Category和SubCategories的菜单,如下所示:
Category1
SubCategory1
SubCategory2
SubCategory3
Category2
SubCategory1
SubCategory2
SubCategory3
Category3
SubCategory1
2 个解决方案
#1
If you set up your PK-FK correctly in DB, LINQ to SQL will do the object association for you. So there will be a property in ProductCategory as an EntitySet of ProductSubCategory.
如果在DB中正确设置PK-FK,LINQ to SQL将为您执行对象关联。因此,ProductCategory中将有一个属性作为ProductSubCategory的EntitySet。
The key is that you DB PK-FK ref must be correct for the LINQ code generator to pick this up.
关键是你的DB PK-FK ref必须正确,LINQ代码生成器才能选择它。
#2
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 put answer 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 note tested syntax. Note that as others have indicated, your primary and foriegn keys must be set up correctly for this to work.
这应该工作(或接近),但我已经测试了语法。请注意,正如其他人指出的那样,必须正确设置主键和外键才能使其正常工作。
#1
If you set up your PK-FK correctly in DB, LINQ to SQL will do the object association for you. So there will be a property in ProductCategory as an EntitySet of ProductSubCategory.
如果在DB中正确设置PK-FK,LINQ to SQL将为您执行对象关联。因此,ProductCategory中将有一个属性作为ProductSubCategory的EntitySet。
The key is that you DB PK-FK ref must be correct for the LINQ code generator to pick this up.
关键是你的DB PK-FK ref必须正确,LINQ代码生成器才能选择它。
#2
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 put answer 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 note tested syntax. Note that as others have indicated, your primary and foriegn keys must be set up correctly for this to work.
这应该工作(或接近),但我已经测试了语法。请注意,正如其他人指出的那样,必须正确设置主键和外键才能使其正常工作。