Linq-to-SQL - 分组和连接

时间:2011-11-19 03:09:10

标签: c# sql linq-to-sql

我有这个架构:

Products (**ProductId**, OwnerId, Name)
Categories (**CategoryId**, Name)
ProductsInCategories( **ProductId**, CategoryId )

当我希望返回类别列表时,Linq很简单:

from c in db.Categories
orderby c.Name
select c;

但是,我想只返回包含具有特定OwnerId的产品的类别集。

如果这是普通的T-SQL,那么我可以轻松地做到这一点:

SELECT ProductsInCategories.CategoryId
FROM ProductsInCategories
INNER JOIN Categories ON ProductsInCategories.CategoryId = ProductsInCategories.CategoryId
INNER JOIN Products   ON ProductsInCategories.ProductId  = Products.ProductId
WHERE Products.OwnerId = 3
GROUP BY ProductsInCategories.CategoryId

(但我注意到这个SQL只返回类别ID但不返回类别名称,理想情况下我想返回两者)

然而,当我将其转换为Linq时,它不再起作用了:

from pic in db.ProductsInCategories
join p in db.Products   on pic.ProductId  equals p.ProductId
join c in db.Categories on pic.CategoryId equals c.CategoryId
orderby c.Name
where p.OwnerId == ownerId
select c;

LinqPad报告这会返回一个包含大量重复条目的大型结果集(每个产品类别映射都会重复类别名称)。

这里有什么解决方案?

谢谢!

2 个答案:

答案 0 :(得分:1)

var q =
    from c in db.Categorie
    where (from pic in db.ProductsInCategories
          join p in db.Products on pic.ProductId equals p.ProductId
          where p.OwnerId == ownerId && pic.CategoryId == c.CategoryId
          select pic).Any()
    select c;

答案 1 :(得分:0)

请运行此SQL语句。如果您获得了真实结果,我们可以将它一起转换为Linq 2 sql

SELECT CategoryId, Name
FROM Categories
WHERE CategoryId IN (SELECT CategoryId FROM ProductsInCategories PIC
                     INNER JOIN Products P ON PIC.ProductId = P.ProductId
                     WHERE P.OwnerID = @OwnerID)