编写复杂的 Linq2SQL 查询
Write a complex Linq2SQL query
我有以下数据
类别
- 类别名称
- 类别ID
产品
- 产品编号
- 产品名称
- 类别ID
项目
- 物品ID
- 物品名称
- 产品编号
查询是什么以便我将获得多个列表,即
ListOfCategory 包含 CategoryName 和 ListOfProduct<>
ListOfProduct 包含 ProductName 和 ListOfItems<>
ListOfItems<> 包含 ItemName 和 ItemID
var cats = (from g in CMP.tblCategories
join proc in CMP.tblProducts
on g.CategoryID equals proc.CategoryID
join item in CMP.tblItems
on proc.ProductID equals item.ProductID
select new { Cat = g.Name, Pro = proc.Name, Itm = item.Name, ItmID = item.ItemID });
我知道这是错误的,所以请帮助我
您可以在 Linq 中使用子查询来简化您的需求。
//获取包含所有详细信息的项目列表
var Items = (from g in CMP.tblCategories
join proc in CMP.tblProducts
on g.CategoryID equals proc.CategoryID
join item in CMP.tblItems
on proc.ProductID equals item.ProductID
select new { Category = g.Name, ProductName = proc.Name, ItemName = item.Name, ItemID = item.ItemID });
//Group by ProductName to get a list of ProductName , List<Items>
var Products = (from i in Items
group i by i.CategoryName into g
select new { CategoryName = g.Key,
Products = (from p in Items
group p by p.ProductName into Productgroup
select new {ProductName = Productgroup.Key, Items = Productgroup})
}).ToList();
我有以下数据
类别
- 类别名称
- 类别ID
产品
- 产品编号
- 产品名称
- 类别ID
项目
- 物品ID
- 物品名称
- 产品编号
查询是什么以便我将获得多个列表,即
ListOfCategory 包含 CategoryName 和 ListOfProduct<>
ListOfProduct 包含 ProductName 和 ListOfItems<>
ListOfItems<> 包含 ItemName 和 ItemID
var cats = (from g in CMP.tblCategories
join proc in CMP.tblProducts
on g.CategoryID equals proc.CategoryID
join item in CMP.tblItems
on proc.ProductID equals item.ProductID
select new { Cat = g.Name, Pro = proc.Name, Itm = item.Name, ItmID = item.ItemID });
我知道这是错误的,所以请帮助我
您可以在 Linq 中使用子查询来简化您的需求。
//获取包含所有详细信息的项目列表
var Items = (from g in CMP.tblCategories
join proc in CMP.tblProducts
on g.CategoryID equals proc.CategoryID
join item in CMP.tblItems
on proc.ProductID equals item.ProductID
select new { Category = g.Name, ProductName = proc.Name, ItemName = item.Name, ItemID = item.ItemID });
//Group by ProductName to get a list of ProductName , List<Items>
var Products = (from i in Items
group i by i.CategoryName into g
select new { CategoryName = g.Key,
Products = (from p in Items
group p by p.ProductName into Productgroup
select new {ProductName = Productgroup.Key, Items = Productgroup})
}).ToList();