【发布时间】:2015-06-22 23:30:58
【问题描述】:
使用 Linq-to-SQL 从 3 个表中获取 NorthWind 数据时遇到问题:
SuppliersProductsCategories
我想获取属于categoryId > 3 类别的所有产品的供应商。结果集将需要每个供应商 1 行,然后是一些子集,其中包含每个产品的一行,包括类别信息。这个想法是这个结果集将作为 ajax 调用的 json 值返回。
以下是我目前最简单的版本:
from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where ( cats.CategoryID > 3)
group sups by sups.SupplierID into g
select g
在 LinqPad 中,结果集似乎包含许多重复的供应商。 有什么想法吗?
编辑: 感谢 Adduci 的回答,我最终得到了以下工作 LINQ 语句:
from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where cats.CategoryID > 3
group new { sups, prods, cats } by new { sups.SupplierID, sups.CompanyName } into g
select new
{
g.Key,
ProductInfo = from x in g
select new
{
ProductProperty = x.prods.ProductName,
CategoryProperty = x.cats.CategoryName
}
}
额外的by new { sups.SupplierID, sups.CompanyName }完成了包括供应商字段的结果集。不错!
【问题讨论】:
标签: c# .net linq linq-to-sql