[英]Linq-to-SQL - Grouping and joins
I have this schema: 我有这个架构:
Products (**ProductId**, OwnerId, Name)
Categories (**CategoryId**, Name)
ProductsInCategories( **ProductId**, CategoryId )
When I wish to return the list of categories the Linq is simple enough: 当我希望返回类别列表时,Linq很简单:
from c in db.Categories
orderby c.Name
select c;
However, I want to return only the set of categories that contain products with a specific OwnerId. 但是,我只想返回一组包含具有特定OwnerId的产品的类别。
If this were normal T-SQL then I can do that easily enough: 如果这是正常的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
(But I note this SQL only returns Category IDs but not Category names as well, ideally I'd like to return both) (但是我注意到此SQL仅返回类别ID,但不返回类别名称,理想情况下,我想同时返回两者)
However when I convert this to Linq it doesn't work anymore: 但是,当我将其转换为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 reports this returns a large result set that contains numerous duplicate entries (category names are repeated for each product-in-category mapping). LinqPad报告这将返回一个很大的结果集,其中包含许多重复的条目(对于每个类别产品映射,都重复了类别名称)。
What's the solution here? 这里有什么解决方案?
Thanks! 谢谢!
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;
Please run this SQL Statement.If you get true result,we can convert it to Linq 2 sql together 请运行此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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.